-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbotmachine.go
More file actions
62 lines (58 loc) · 1.31 KB
/
Copy pathbotmachine.go
File metadata and controls
62 lines (58 loc) · 1.31 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
package botmeans
import (
"time"
)
//Executer is a executable operation
type Executer interface {
Id() int64
Execute()
}
//RunMachine creates the machine, which executes Executers in parallel, but Executers with the same id are executed serially
func RunMachine(queueStream chan Executer, interval time.Duration) chan interface{} {
stopChan := make(chan interface{})
queueChanMap := make(map[int64]chan Executer)
handlerClosedChan := make(chan int64)
handler := func(ch chan Executer, ID int64) {
defer func() {
if r := recover(); r != nil {
handlerClosedChan <- ID
}
}()
exitSignaller := time.After(interval)
for {
select {
case queue := <-ch:
queue.Execute()
exitSignaller = time.After(interval)
case <-exitSignaller:
handlerClosedChan <- ID
return
}
}
}
go func() {
for {
select {
case queue := <-queueStream:
if queue == nil {
continue
}
ID := queue.Id()
var queueChan chan Executer
ok := false
if queueChan, ok = queueChanMap[ID]; !ok {
queueChan = make(chan Executer)
queueChanMap[ID] = queueChan
go handler(queueChan, ID)
}
// go func() { queueChan <- queue }()
queueChan <- queue
case id := <-handlerClosedChan:
delete(queueChanMap, id)
case <-stopChan:
return
}
}
}()
return stopChan
}