-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrsched.go
53 lines (46 loc) · 1.3 KB
/
scrsched.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
package scriptmanager
import (
"context"
"github.com/pkg/errors"
"time"
)
type scriptScheduler struct {
jobChan chan scriptJob
}
func newScriptScheduler() *scriptScheduler {
ss := &scriptScheduler{}
ss.start()
return ss
}
func (ss *scriptScheduler) start() {
ss.jobChan = make(chan scriptJob)
go func() {
for job := range ss.jobChan {
job.job(job.ctx)
}
}()
}
// startJobOnceFree will submit a script execution job. The function will wait until the scheduler is free.
// The job will then run on the script goroutine and the function will return.
func (ss *scriptScheduler) startJobOnceFree(ctx context.Context, job func(ctx context.Context)) error {
select {
case ss.jobChan <- scriptJob{ctx: ctx, job: job}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// runNow will submit a job for immediate execution. The job will run as long as the scheduler is free.
// If the scheduler is not free, an error will be returned and the job will not run.
func (ss *scriptScheduler) runNow(ctx context.Context, job func(ctx context.Context)) error {
select {
case ss.jobChan <- scriptJob{ctx: ctx, job: job}:
return nil
case <-time.After(500 * time.Millisecond):
return errors.New("a script is already running")
}
}
type scriptJob struct {
ctx context.Context
job func(ctx context.Context)
}