-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskflow.go
More file actions
80 lines (72 loc) · 2.07 KB
/
taskflow.go
File metadata and controls
80 lines (72 loc) · 2.07 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
68
69
70
71
72
73
74
75
76
77
78
79
80
package taskflow
import (
"context"
"sync"
"time"
)
type TaskFlow struct {
cfg *Config
mgr *Manager // We set this once we start workers
handlers map[Operation]JobHandler
advancedHandlers map[Operation]AdvancedJobConstructor
handlerMu sync.RWMutex
}
func New(cfg Config) *TaskFlow {
// Provide default log functions if the user didn't set them
if cfg.InfoLog == nil {
cfg.InfoLog = defaultInfoLog
}
if cfg.ErrorLog == nil {
cfg.ErrorLog = defaultErrorLog
}
return &TaskFlow{
cfg: &cfg,
handlers: make(map[Operation]JobHandler),
advancedHandlers: make(map[Operation]AdvancedJobConstructor),
}
}
// CreateJob inserts a new job into the database
func (tf *TaskFlow) CreateJob(ctx context.Context, operation Operation, payload any, executeAt time.Time) (int64, error) {
// Actually insert the job
id, err := createJob(ctx, tf, operation, payload, executeAt)
if err != nil {
return 0, err
}
// If the job is ready now
if executeAt.Before(time.Now()) {
// Send a wakeup signal to let workers check immediately
if tf.mgr != nil {
select {
case tf.mgr.wakeup <- struct{}{}:
// wake worker
default:
// channel is full or no manager; ignore
}
}
}
return id, nil
}
// StartWorkers spawns `count` workers to process jobs using the current config.
// It returns immediately, but you can call Shutdown(...) later to stop them.
func (tf *TaskFlow) StartWorkers(ctx context.Context, count int) {
if tf.mgr != nil {
tf.cfg.logError(LogEvent{
Message: "Workers already started on this TaskFlow instance.",
})
return
}
mgr := startWorkersInternal(ctx, count, tf.cfg, tf.handlers, tf.advancedHandlers)
tf.mgr = mgr
}
// Shutdown gracefully stops all workers, waiting up to `timeout` for them to exit.
func (tf *TaskFlow) Shutdown(timeout time.Duration) {
if tf.mgr == nil {
tf.cfg.logInfo(LogEvent{
Message: "No workers to shut down (did you call StartWorkers?).",
})
return
}
tf.mgr.Shutdown(timeout)
tf.mgr = nil
tf.cfg.logInfo(LogEvent{Message: "TaskFlow shutdown complete."})
}