-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
73 lines (58 loc) · 1.28 KB
/
main.go
File metadata and controls
73 lines (58 loc) · 1.28 KB
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
package main
import (
"context"
"fmt"
"math/rand"
"time"
"github.com/SamuelTissot/bqueue"
)
// AJob is a struct that implement the bqueue.Job interface
type AJob struct {
id int
}
// Process implements bqueue.Job
func (j *AJob) Process() {
// simulate work duration to show that the jobs are not sequentials
duration := workDuration()
time.Sleep(duration)
fmt.Printf(
"processed job: %d, job took: %d milliseconds\n",
j.id,
duration.Milliseconds(),
)
}
func main() {
// Create the Queue with 2 static worker
q, err := bqueue.New(bqueue.Static(), bqueue.Workers(2))
if err != nil {
// handle error
panic(err)
}
// blocking until all jobs are added
addJobsAsync(q)
// will wait until all jobs are done to STOP or the context is cancelled.
if err := q.Stop(context.TODO()); err != nil {
// handle error
panic(err)
}
}
// addJobsAsync simulates job comming in randomly
// it will add 50 jobs
func addJobsAsync(q *bqueue.Queue) {
ticker := time.NewTicker(10 * time.Millisecond)
id := 1
for range ticker.C {
if id > 50 {
return
}
q.Queue(&AJob{
id: id,
})
id++
}
}
// workDuration is a helpeer function to simulate work time
func workDuration() time.Duration {
mult := rand.Intn(1000-100) + 100
return time.Millisecond * time.Duration(mult)
}