task

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 14, 2023 License: MPL-2.0 Imports: 4 Imported by: 4

Documentation

Overview

Package task provides some helper to work with simple routine.

Functions and methods which requires a task accepts raw Task type for best compatibility. Those create task returns Helper instead so it's easier to use.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Sleep

func Sleep(ctx context.Context, timeout time.Duration) error

Sleep is a cancellable time.Sleep.

Types

type CtxMod

type CtxMod func(context.Context) (context.Context, func())

CtxMod defines how you modify a context.

func WithTimeout

func WithTimeout(dur time.Duration) CtxMod

WithTimeout creates a CtxMod which adds timeout info to a context.

type Func

type Func func(context.Context) error

Func converts specific function into task.

func (Func) Helper

func (t Func) Helper() Helper

Helper creates a Helper.

func (Func) Run

func (t Func) Run(ctx context.Context) error

Run runs the task, equals to t(ctx).

type Helper

type Helper struct{ Task }

Helper provides some useful tools.

func Copy

func Copy(dst io.Writer, src io.ReadCloser) Helper

Copy wraps io.Copy into a cancellable task. Cancelling context will close src.

func F

func F(f func(context.Context) error) Helper

F is shortcut to Func(f).Helper()

func FromServer

func FromServer(start func() error, stop func()) Helper

FromServer creates a task from server, which can be started or stopped. Running the task calls start, and cancelling context calls stop.

func HTTPServer

func HTTPServer(s *http.Server, shutdown ...CtxMod) Helper

HTTPServer wraps s into a task so it can shutdown gracefully when canceled.

func Iter

func Iter(tasks ...Task) Helper

Iter creates a task run tasks with same context and stops at first error.

Example
e := errors.New("err")
a := F(func(_ context.Context) error { fmt.Println("a"); return nil })
b := F(func(_ context.Context) error { fmt.Println("b"); return e })
c := F(func(_ context.Context) error { fmt.Println("c"); return nil })

err := Iter(a, b, c).Run(context.Background())
if err != e {
	fmt.Println("unexpected error:", err)
	return
}
Output:

a
b

func IterF

func IterF(tasks ...func(context.Context) error) Helper

IterF is helper to run Iter.

func Skip

func Skip(tasks ...Task) Helper

Skip creates a task that runs tasks concurrently, cancel others if any error, and wait them done.

func SkipF

func SkipF(tasks ...func(context.Context) error) Helper

SkipF is helper to run Skip.

func T

func T(t Task) Helper

T wraps t into Helper.

func Wait

func Wait(tasks ...Task) Helper

Wait creates a task that runs all task concurrently, wait them get done, and return first non-nil error.

func WaitF

func WaitF(tasks ...func(context.Context) error) Helper

WaitF is helper to run Wait.

func (Helper) Go

func (t Helper) Go(ctx context.Context) <-chan error

Go runs t in separated goroutine and returns a channel to retrieve error.

func (Helper) GoWithChan

func (t Helper) GoWithChan(ctx context.Context, ch chan<- error)

GoWithChan runs t in separated goroutine and sends returned error into ch.

func (Helper) HandleErr

func (t Helper) HandleErr(f func(error) error) Helper

HandleErr creates a task that handles specific error after running t. It will change the error returned by Run. f is called only if t.Run returns an error.

func (Helper) IgnoreErr

func (t Helper) IgnoreErr() Helper

IgnoreErr ignores the error returned by t.Run. Context errors are unmodified.

func (Helper) Loop

func (t Helper) Loop() Helper

Loop creates a task that repeatedly runs t with same context until it returns an error.

func (Helper) Retry

func (t Helper) Retry() Helper

Retry creates a task thats repeatedly runs t with same context until it returns nil.

func (Helper) RetryN

func (t Helper) RetryN(n int) Helper

RetryN is like Retry, but retries no more than n times.

In other words, RetryN(2) will run at most 3 times:

  • first try
  • first retry
  • second retry
Example
ctx := context.Background()
n := 1
errTask := func(_ context.Context) error {
	fmt.Println(n)
	n++
	return errors.New("")
}

retry := F(errTask).RetryN(2)
retry.Run(ctx)
Output:

1
2
3

func (Helper) Timed

func (t Helper) Timed(dur time.Duration) Helper

Timed wraps t into a task ensures that it is not returned before dur passed.

It focuses on "How long I should wait before returning". Take a look at example for how it works.

If you're looking for rate limiting solution, you should take a look at "rated" subdirectory.

Example
ctx := context.Background()
begin := time.Now()
quickTask := F(func(_ context.Context) error {
	// simulates a quick task like computing 1+1
	fmt.Printf("quick done at +%d socond\n", time.Since(begin)/time.Second)
	return nil
}).Timed(time.Second)
quickTask.Run(ctx)
fmt.Printf("quick returns at +%d second\n", time.Since(begin)/time.Second)

begin = time.Now()
slowTask := F(func(_ context.Context) error {
	// simulates a slow task like calling web api
	time.Sleep(2 * time.Second)
	fmt.Printf("slow done at +%d socond\n", time.Since(begin)/time.Second)
	return nil
}).Timed(time.Second)
slowTask.Run(ctx)
fmt.Printf("slow returns at +%d second\n", time.Since(begin)/time.Second)
Output:

quick done at +0 socond
quick returns at +1 second
slow done at +2 socond
slow returns at +2 second

func (Helper) TimedDone

func (t Helper) TimedDone(dur time.Duration) Helper

TimedDone is like Timed, but limits only successful run.

If you're looking for rate limiting solution, you should take a look at "rated" subdirectory.

Example
ctx := context.Background()
begin := time.Now()
doneTask := F(func(_ context.Context) error {
	// a task which always success
	return nil
}).TimedDone(time.Second)
doneTask.Run(ctx)
fmt.Printf("done returns at +%d second\n", time.Since(begin)/time.Second)

begin = time.Now()
failTask := F(func(_ context.Context) error {
	return errors.New("a task which always fail")
}).TimedDone(time.Second)
failTask.Run(ctx)
fmt.Printf("fail returns at +%d second\n", time.Since(begin)/time.Second)
Output:

done returns at +1 second
fail returns at +0 second

func (Helper) TimedDoneF

func (t Helper) TimedDoneF(f func(time.Duration) time.Duration) Helper

TimedDoneF is like TimedDone, but use function instead.

func (Helper) TimedF

func (t Helper) TimedF(f func(time.Duration) time.Duration) Helper

TimedF is like Timed, but use function instead.

func (Helper) TimedFail

func (t Helper) TimedFail(dur time.Duration) Helper

TimedFail is like Timed, but limits only failed run.

If you're looking for rate limiting solution, you should take a look at "rated" subdirectory.

func (Helper) TimedFailF

func (t Helper) TimedFailF(f func(time.Duration) time.Duration) Helper

TimedFailF is like TimedFail, but use function instead.

func (Helper) With

func (t Helper) With(modder CtxMod) Helper

With creates a task that the context is derived using modder before running t.

type Task

type Task interface {
	// Run runs the task.
	Run(context.Context) error
}

Task repeasents a (maybe) cancellable routine.

Directories

Path Synopsis
Package deptask provides a tool, [Runner], to run tasks in order according to its dependency.
Package deptask provides a tool, [Runner], to run tasks in order according to its dependency.
Package future defines [Future], a value which is determined some time in future.
Package future defines [Future], a value which is determined some time in future.
Package rated controls rate of a task with [rate.Limiter].
Package rated controls rate of a task with [rate.Limiter].

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL