forked from bcongdon/corral
/
BackoffPolling.go
50 lines (45 loc) 路 1.08 KB
/
BackoffPolling.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 polling
import (
"context"
"github.com/ISE-SMILE/corral/api"
log "github.com/sirupsen/logrus"
"time"
)
type BackoffPolling struct {
backoffCounter map[string]int
}
func (b *BackoffPolling) StartJob(info api.JobInfo) error {
log.Debug(info)
b.backoffCounter = make(map[string]int)
return nil
}
func (b *BackoffPolling) TaskUpdate(info api.TaskInfo) error {
log.Debug(info)
if info.Completed || info.Failed {
if _, ok := b.backoffCounter[info.RId]; ok {
delete(b.backoffCounter, info.RId)
}
}
return nil
}
func (b *BackoffPolling) Poll(context context.Context, RId string) (<-chan interface{}, error) {
var backoff int
if last, ok := b.backoffCounter[RId]; ok {
b.backoffCounter[RId] = last + 1
backoff = last
} else {
backoff = 4
b.backoffCounter[RId] = backoff
}
log.Debugf("Poll backoff %s for %d seconds", RId, backoff*backoff)
channel := make(chan interface{})
go func() {
select {
case <-context.Done():
channel <- struct{}{}
case <-time.After(time.Second * time.Duration(backoff*backoff)):
channel <- struct{}{}
}
}()
return channel, nil
}