forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pinger.go
77 lines (62 loc) · 1.48 KB
/
pinger.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
// Copyright 2017 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"sync"
"time"
"github.com/keybase/client/go/logger"
"golang.org/x/net/context"
)
// pinger is a helper type that calls a given function periodically.
type pinger struct {
name string
doPing func(ctx context.Context)
timeout time.Duration
log logger.Logger
tickerMu sync.Mutex
tickerCancel context.CancelFunc
}
func (p *pinger) pingOnce(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, p.timeout)
defer cancel()
p.doPing(ctx)
}
func (p *pinger) cancelTicker() {
p.tickerMu.Lock()
defer p.tickerMu.Unlock()
if p.tickerCancel != nil {
p.tickerCancel()
p.tickerCancel = nil
}
}
func (p *pinger) resetTicker(intervalSeconds int) {
p.tickerMu.Lock()
defer p.tickerMu.Unlock()
if p.tickerCancel != nil {
p.tickerCancel()
p.tickerCancel = nil
}
p.log.CDebugf(context.TODO(),
"%s: Starting new ping ticker with interval %d", p.name,
intervalSeconds)
var ctx context.Context
ctx, p.tickerCancel = context.WithCancel(context.Background())
go func() {
p.pingOnce(ctx)
if intervalSeconds <= 0 {
return
}
ticker := time.NewTicker(time.Duration(intervalSeconds) * time.Second)
for {
select {
case <-ticker.C:
p.pingOnce(ctx)
case <-ctx.Done():
p.log.CDebugf(ctx, "%s: stopping ping ticker", p.name)
ticker.Stop()
return
}
}
}()
}