-
Notifications
You must be signed in to change notification settings - Fork 0
/
timed_pool.go
97 lines (80 loc) · 2.32 KB
/
timed_pool.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package workerpool
import (
"context"
"time"
)
// Dispatcher - the function is called by timer for receiving tasks
type Dispatcher[Task any] func(ctx context.Context) ([]Task, error)
// ErrorHandler - the function is called when error occured in dispatcher
type ErrorHandler[Task any] func(ctx context.Context, err error)
// TimedPool - worker pool which receives task by executing `dispatcher` function by ticker.
type TimedPool[Task any] struct {
*Pool[Task]
dispatcher Dispatcher[Task]
errorHandler ErrorHandler[Task]
periodReceivingTasks time.Duration
}
// NewTimedPool - creates new `TimedPool`.
// `dispatcher` - is a function returning tasks. If it's null `Start` function immidiately exits.
// `worker` - is a job executing by a task.
// `errorHandler` - callback to error handling in `dispatcher` executing. May be null.
// `workersCount` - count of workers executing jobs.
// `periodReceivingTasks` - ticker period in milliseconds when `dispatcher` will be called.
func NewTimedPool[Task any](
dispatcher Dispatcher[Task],
worker Worker[Task],
errorHandler ErrorHandler[Task],
workersCount int,
periodReceivingTasks int,
) *TimedPool[Task] {
return &TimedPool[Task]{
Pool: NewPool(worker, workersCount),
dispatcher: dispatcher,
errorHandler: errorHandler,
periodReceivingTasks: time.Millisecond * time.Duration(periodReceivingTasks),
}
}
// Start - starts pool and dispatcher.
func (pool *TimedPool[Task]) Start(ctx context.Context) {
if pool.dispatcher == nil {
return
}
pool.Pool.Start(ctx)
pool.wg.Add(1)
go pool.dispatch(ctx)
}
func (pool *TimedPool[Task]) dispatch(ctx context.Context) {
defer pool.wg.Done()
ticker := time.NewTicker(pool.periodReceivingTasks)
defer ticker.Stop()
// First tick
pool.tick(ctx, ticker)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
pool.tick(ctx, ticker)
}
}
}
func (pool *TimedPool[Task]) tick(ctx context.Context, ticker *time.Ticker) {
tasks, err := pool.dispatcher(ctx)
if err != nil && pool.errorHandler != nil {
pool.errorHandler(ctx, err)
return
}
if len(tasks) == 0 {
ticker.Reset(pool.periodReceivingTasks * 10)
return
}
for i := range tasks {
select {
case <-ctx.Done():
return
default:
pool.Pool.AddTask(tasks[i])
}
}
ticker.Reset(pool.periodReceivingTasks)
}