Skip to content

Commit ab74b9d

Browse files
authored
Add select wrapper (#158)
Better handling of job delay --------- Co-authored-by: samyfodil <[email protected]>
1 parent 186edae commit ab74b9d

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

protocols/monkey/jobs/run.go

+8-2
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@ package jobs
22

33
import (
44
"context"
5+
"errors"
56
"time"
67

78
"github.com/ipfs/go-log/v2"
89
)
910

1011
var (
11-
logger = log.Logger("tau.monkey.jobs.client")
12+
logger = log.Logger("tau.monkey.jobs.client")
13+
ErrorContextCanceled = errors.New("context cancel")
1214
)
1315

1416
func (c *Context) Run(ctx context.Context, ctxC context.CancelFunc) (err error) {
@@ -17,7 +19,11 @@ func (c *Context) Run(ctx context.Context, ctxC context.CancelFunc) (err error)
1719
defer ctxC()
1820

1921
if c.Job.Delay != nil {
20-
<-time.After(time.Duration(c.Job.Delay.Time) * time.Second)
22+
select {
23+
case <-time.After(time.Duration(c.Job.Delay.Time) * time.Second):
24+
case <-c.ctx.Done():
25+
return ErrorContextCanceled
26+
}
2127
}
2228

2329
if err = c.cloneAndSet(); err != nil {

protocols/monkey/jobs/run_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package jobs
2+
3+
import (
4+
"context"
5+
"testing"
6+
"time"
7+
8+
"github.com/taubyte/go-interfaces/services/patrick"
9+
"gotest.tools/v3/assert"
10+
)
11+
12+
func TestRunDelay(t *testing.T) {
13+
c := &Context{
14+
Job: &patrick.Job{
15+
Delay: &patrick.DelayConfig{
16+
Time: 300,
17+
},
18+
},
19+
}
20+
21+
ctx, ctxC := context.WithTimeout(context.Background(), 1*time.Second)
22+
err := c.Run(ctx, ctxC)
23+
assert.Equal(t, err, ErrorContextCanceled)
24+
}

0 commit comments

Comments
 (0)