/
interruptible_task.go
54 lines (43 loc) · 1.12 KB
/
interruptible_task.go
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
package common
import (
"time"
)
type InterruptibleTaskResult struct {
Err error
IsCancelled bool
}
type InterruptibleTask struct {
IsCancelled func() bool
Task func(cancelCh <-chan struct{}) error
}
func NewInterruptibleTask(isCancelled func() bool, task func(cancelCh <-chan struct{}) error) *InterruptibleTask {
return &InterruptibleTask{
IsCancelled: isCancelled,
Task: task,
}
}
func StartInterruptibleTask(isCancelled func() bool, task func(cancelCh <-chan struct{}) error) InterruptibleTaskResult {
t := NewInterruptibleTask(isCancelled, task)
return t.Run()
}
func (s *InterruptibleTask) Run() InterruptibleTaskResult {
completeCh := make(chan error)
cancelCh := make(chan struct{})
defer close(cancelCh)
go func() {
err := s.Task(cancelCh)
completeCh <- err
// senders close, receivers check for close
close(completeCh)
}()
for {
if s.IsCancelled() {
return InterruptibleTaskResult{Err: nil, IsCancelled: true}
}
select {
case err := <-completeCh:
return InterruptibleTaskResult{Err: err, IsCancelled: false}
case <-time.After(100 * time.Millisecond):
}
}
}