-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
58 lines (46 loc) · 989 Bytes
/
main.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
package main
import (
"log"
"math/rand"
"time"
"github.com/Jeffail/tunny"
)
var pool *tunny.Pool
type Job struct {
Data string
}
func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}
func main() {
pool = tunny.NewFunc(runtime.NumCPU(), worker)
defer pool.Close()
for i := 0; i < 100; i++ {
postJob(time.Now().String())
}
select {}
}
func worker(work interface{}) interface{} {
switch w := work.(type) {
case *Job:
return w.build()
}
return "Couldn't find work type"
}
func (j *Job) build() string {
log.Printf("Starting to process job %s ", j.Data)
time.Sleep(time.Duration(random(1, 3)) * time.Second)
log.Printf("Done %v", j.Data)
return "OK"
}
func postJob(value string) {
go processJob(pool, value)
}
func processJob(pool *tunny.Pool, data string) {
j := &Job{Data: data}
_, err := pool.ProcessTimed(j, time.Minute*30)
if err == tunny.ErrJobTimedOut {
log.Printf("problem to process job %v", err)
}
}