-
Notifications
You must be signed in to change notification settings - Fork 7
/
job.go
57 lines (47 loc) · 1.13 KB
/
job.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
package main
import (
"fmt"
"time"
"github.com/pcelvng/task"
"github.com/pcelvng/task-tools/tmpl"
"github.com/pcelvng/task/bus"
"github.com/robfig/cron/v3"
)
// makeCron will create the cron and setup all the cron jobs.
// It will not start the cron.
func makeCron(rules []Rule, producer bus.Producer) (*cron.Cron, error) {
c := cron.New(cron.WithSeconds())
for _, rule := range rules {
job := newJob(rule, producer)
if _, err := c.AddJob(rule.CronRule, job); err != nil {
return nil, fmt.Errorf("cron: '%s' '%v'", rule.CronRule, err.Error())
}
}
return c, nil
}
func newJob(rule Rule, p bus.Producer) *job {
// normalize topic
if rule.Topic == "" {
rule.Topic = rule.TaskType
}
return &job{
Rule: rule,
p: p,
}
}
type job struct {
Rule
p bus.Producer
}
func (j *job) Run() {
// make task
info := tmpl.Parse(j.TaskTemplate, offsetDate(j.HourOffset))
tsk := task.New(j.TaskType, info)
j.p.Send(j.Topic, tsk.JSONBytes())
}
// offsetDate will return the time.Time value with the
// hour offset.
func offsetDate(offset int) time.Time {
now := time.Now()
return now.Add(time.Hour * time.Duration(offset))
}