forked from Fantom-foundation/Sonic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtflusher.go
47 lines (40 loc) · 774 Bytes
/
tflusher.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
package gossip
import (
"sync"
"time"
)
type PeriodicFlusherCallaback struct {
busy func() bool
commitNeeded func() bool
commit func()
}
// PeriodicFlusher periodically commits the Store if isCommitNeeded returns true
type PeriodicFlusher struct {
period time.Duration
callback PeriodicFlusherCallaback
wg sync.WaitGroup
quit chan struct{}
}
func (c *PeriodicFlusher) loop() {
defer c.wg.Done()
ticker := time.NewTicker(c.period)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if !c.callback.busy() && c.callback.commitNeeded() {
c.callback.commit()
}
case <-c.quit:
return
}
}
}
func (c *PeriodicFlusher) Start() {
c.wg.Add(1)
go c.loop()
}
func (c *PeriodicFlusher) Stop() {
close(c.quit)
c.wg.Wait()
}