-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrapper.go
More file actions
72 lines (65 loc) · 1.55 KB
/
Copy pathwrapper.go
File metadata and controls
72 lines (65 loc) · 1.55 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
package cronlib
import (
"context"
"fmt"
"sync"
)
// Chain combines multiple job wrappers into a single wrapper.
// Wrappers are executed in the order they are passed.
// Example: Chain(W1, W2) results in W1(W2(Job)).
func Chain(wrappers ...JobWrapper) JobWrapper {
return func(next JobCmd) JobCmd {
for i := len(wrappers) - 1; i >= 0; i-- {
next = wrappers[i](next)
}
return next
}
}
// Recover creates a wrapper that catches panics and returns them as errors.
func Recover() JobWrapper {
return func(next JobCmd) JobCmd {
return func(ctx context.Context) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
return next(ctx)
}
}
}
// DelayIfStillRunning ensures that job executions are sequential.
// If a job is triggered while a previous instance is running, it waits.
func DelayIfStillRunning() JobWrapper {
var mu sync.Mutex
return func(next JobCmd) JobCmd {
return func(ctx context.Context) error {
mu.Lock()
defer mu.Unlock()
return next(ctx)
}
}
}
// SkipIfStillRunning skips execution if the previous instance is still running.
// This is an alternative to the OverlapForbid policy, implemented as a wrapper.
func SkipIfStillRunning() JobWrapper {
var mu sync.Mutex
var running bool
return func(next JobCmd) JobCmd {
return func(ctx context.Context) error {
mu.Lock()
if running {
mu.Unlock()
return nil
}
running = true
mu.Unlock()
defer func() {
mu.Lock()
running = false
mu.Unlock()
}()
return next(ctx)
}
}
}