-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhooks.go
More file actions
69 lines (56 loc) · 1.49 KB
/
hooks.go
File metadata and controls
69 lines (56 loc) · 1.49 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
package worker
import (
"log/slog"
"time"
)
// TaskHooks defines optional callbacks for task lifecycle events.
type TaskHooks struct {
OnQueued func(task *Task)
OnStart func(task *Task)
OnFinish func(task *Task, status TaskStatus, result any, err error)
OnRetry func(task *Task, delay time.Duration, attempt int)
}
// SetHooks configures callbacks for task lifecycle events.
func (tm *TaskManager) SetHooks(hooks TaskHooks) {
h := hooks
tm.hooks.Store(&h)
}
func (tm *TaskManager) hookQueued(task *Task) {
hooks := tm.hooks.Load()
if hooks == nil || hooks.OnQueued == nil {
return
}
runHook(func() { hooks.OnQueued(task) })
}
func (tm *TaskManager) hookStart(task *Task) {
hooks := tm.hooks.Load()
if hooks == nil || hooks.OnStart == nil {
return
}
runHook(func() { hooks.OnStart(task) })
}
func (tm *TaskManager) hookFinish(task *Task, status TaskStatus, result any, err error) {
hooks := tm.hooks.Load()
if hooks == nil || hooks.OnFinish == nil {
return
}
runHook(func() { hooks.OnFinish(task, status, result, err) })
}
func (tm *TaskManager) hookRetry(task *Task, delay time.Duration, attempt int) {
hooks := tm.hooks.Load()
if hooks == nil || hooks.OnRetry == nil {
return
}
runHook(func() { hooks.OnRetry(task, delay, attempt) })
}
func runHook(fn func()) {
defer func() {
err := recover()
if err != nil {
logger := slog.Default()
// Log the panic from the hook to avoid crashing the task manager.
logger.Error("task hook panic", "error", err)
}
}()
fn()
}