-
Notifications
You must be signed in to change notification settings - Fork 98
/
jobrunner.go
80 lines (65 loc) · 1.26 KB
/
jobrunner.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
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 jobrunner
import (
"bytes"
"log"
"reflect"
"runtime/debug"
"sync"
"sync/atomic"
"time"
"github.com/robfig/cron/v3"
)
type Job struct {
Name string
inner cron.Job
status uint32
Status string
Latency string
running sync.Mutex
}
const UNNAMED = "(unnamed)"
func New(job cron.Job) *Job {
name := reflect.TypeOf(job).Name()
if name == "Func" {
name = UNNAMED
}
return &Job{
Name: name,
inner: job,
}
}
func (j *Job) StatusUpdate() string {
if atomic.LoadUint32(&j.status) > 0 {
j.Status = "RUNNING"
return j.Status
}
j.Status = "IDLE"
return j.Status
}
func (j *Job) Run() {
start := time.Now()
// If the job panics, just print a stack trace.
// Don't let the whole process die.
defer func() {
if err := recover(); err != nil {
var buf bytes.Buffer
logger := log.New(&buf, "JobRunner Log: ", log.Lshortfile)
logger.Panic(err, "\n", string(debug.Stack()))
}
}()
if !selfConcurrent {
j.running.Lock()
defer j.running.Unlock()
}
if workPermits != nil {
workPermits <- struct{}{}
defer func() { <-workPermits }()
}
atomic.StoreUint32(&j.status, 1)
j.StatusUpdate()
defer j.StatusUpdate()
defer atomic.StoreUint32(&j.status, 0)
j.inner.Run()
end := time.Now()
j.Latency = end.Sub(start).String()
}