This repository has been archived by the owner on Feb 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
60 lines (51 loc) · 1.6 KB
/
worker.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
package dhelpers
import (
"context"
"time"
"github.com/bsm/redis-lock"
"gitlab.com/Cacophony/dhelpers/cache"
"gitlab.com/Cacophony/dhelpers/net"
)
// Job defines setting for a job
type Job struct {
// Name should be unique, prefixed by module
Name string
// Cron is a cron expression https://godoc.org/github.com/robfig/cron#hdr-CRON_Expression_Format, https://crontab.guru/
Cron string
// AtLaunch if set to true will start the Job at launch
AtLaunch bool
Job func()
}
func jobLockKey(jobName string) (key string) {
return "project-d:job:" + jobName + ":status"
}
// JobStart returns true and a locker if the Job has been started successfully, returns false if the Job is already running
// after timeout the locks unlock itself, use locker.Lock() to renew a lock
func JobStart(jobName string, timeout time.Duration) (start bool, locker *lock.Locker, err error) {
locker = lock.New(cache.GetRedisClient(), jobLockKey(jobName), &lock.Options{
LockTimeout: timeout,
RetryCount: 0,
RetryDelay: 100 * time.Millisecond,
})
// lock locker
start, err = locker.LockWithContext(context.Background())
return start, locker, err
}
// JobFinishSuccess calls the healthcheck if exists
func JobFinishSuccess(healthcheckURL string) error {
if healthcheckURL != "" {
_, err := net.Get(healthcheckURL)
if err != nil {
return err
}
}
return nil
}
// JobErrorHandler handles errors at jobs, defer to this: defer JobErrorHandler(jobName)
func JobErrorHandler(jobName string) {
err := recover()
if err != nil {
// handle errors
HandleJobErrorWith("Worker", jobName, err.(error), SentryErrorHandler)
}
}