-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.go
79 lines (65 loc) · 1.76 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Package hjob contains interfaces to
// define workers to process background
// jobs.
//--------------------------------
package hjob
import (
"context"
"encoding/json"
"time"
"github.com/kamva/hexa"
)
// JobHandlerFunc is the handler of each job in the worker.
type JobHandlerFunc func(context.Context, Payload) error
type Payload interface {
Decode(payload interface{}) error
}
// Job is a new instance of job to push to the queue by Jobs interface
type Job struct {
Name string // required
Queue string
// Retry specify retry counts of the job.
// 0: means that throw job away (and dont push to dead queue) on first fail.
// -1: means that push job to the dead queue on first fail.
Retry int
Timeout time.Duration
Payload interface{} // It can be any struct.
}
// Worker is the background jobs worker
type Worker interface {
// Register handler for new job
Register(name string, handlerFunc JobHandlerFunc) error
hexa.Runnable
}
// Jobs pushes jobs to process by worker.
type Jobs interface {
// Push push job to the default queue
Push(context.Context, *Job) error
}
// NewJob returns new job instance
func NewJob(name string, payload interface{}) *Job {
return NewJobWithQueue(name, "default", payload)
}
// NewJobWithQueue returns new job instance
func NewJobWithQueue(name string, queue string, p interface{}) *Job {
return &Job{
Name: name,
Queue: queue,
Retry: 4,
Timeout: time.Minute * 30,
Payload: p,
}
}
//--------------------------------
// Json payload implementation
//--------------------------------
type jsonPayload struct {
p []byte
}
func (j *jsonPayload) Decode(val interface{}) error {
return json.Unmarshal(j.p, val)
}
func NewJsonPayload(p []byte) Payload {
return &jsonPayload{p: p}
}
var _ Payload = &jsonPayload{}