forked from go-telegram/bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait_updates.go
50 lines (42 loc) · 999 Bytes
/
wait_updates.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
package bot
import (
"context"
"sync"
"time"
"github.com/go-telegram/bot/models"
)
// waitUpdates listen Updates channel and spawn goroutines if needed. It's a simple worker pool
func (b *Bot) waitUpdates(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
taskQueue := make(chan *models.Update)
for {
select {
case <-ctx.Done():
return
case upd := <-b.updates:
select {
case taskQueue <- upd:
default:
wg.Add(1)
go func(ctx context.Context, wg *sync.WaitGroup, taskQueue chan *models.Update) {
defer wg.Done()
b.ProcessUpdate(ctx, upd)
const cleanupDuration = 10 * time.Second
cleanupTicker := time.NewTicker(cleanupDuration)
defer cleanupTicker.Stop()
for {
select {
case <-ctx.Done():
return
case upd := <-taskQueue:
b.ProcessUpdate(ctx, upd)
cleanupTicker.Reset(cleanupDuration)
case <-cleanupTicker.C:
return
}
}
}(ctx, wg, taskQueue)
}
}
}
}