-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc.go
More file actions
67 lines (59 loc) · 1.31 KB
/
func.go
File metadata and controls
67 lines (59 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package task
import (
"context"
"time"
)
// NoCtx wraps a non-cancellable function into task.
func NoCtx(f func() error) Task {
return func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return f()
}
}
}
// NoErr wraps a never-fail, non-cancellable function into task.
func NoErr(f func()) Task {
return func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
f()
return nil
}
}
}
// Sleep is a cancellable [time.Sleep] in task form.
func Sleep(timeout time.Duration) Task {
return func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(timeout):
return nil
}
}
}
// FromServer creates a task from something can be started or stopped. Running
// the task calls start, and cancelling context calls stop.
func FromServer(start func() error, stop func()) Task {
return func(ctx context.Context) error {
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-done:
return
case <-ctx.Done():
}
stop()
}()
return start()
}
}