Remove time.Ticker and adjust polling mechanism
[pstop.git] / wait_info / wait_info.go
1 package wait_info
2
3 import (
4         "github.com/sjmudd/pstop/lib"
5         "time"
6 )
7
8 const extra_delay = 200 * time.Millisecond
9
10 // used to record when we need to wa
11 type WaitInfo struct {
12         last_collected   time.Time
13         collect_interval time.Duration
14 }
15
16 // return the configured wait interval
17 func (wi *WaitInfo) WaitInterval() time.Duration {
18         return wi.collect_interval
19 }
20
21 // recognise we've done a collection
22 func (wi *WaitInfo) CollectedNow() {
23         wi.SetCollected(time.Now())
24 }
25
26 // change the configured wait interval
27 func (wi *WaitInfo) SetWaitInterval(required_interval time.Duration) {
28         wi.collect_interval = required_interval
29 }
30
31 // set the time the last collection happened
32 func (wi *WaitInfo) SetCollected(collect_time time.Time) {
33         wi.last_collected = collect_time
34         lib.Logger.Println("WaitInfo.SetCollected() last_collected=", wi.last_collected)
35 }
36
37 // return the time the last collection happened
38 func (wi WaitInfo) LastCollected() time.Time {
39         return wi.last_collected
40 }
41
42 // return the amount of time to wait before doing the next collection
43 func (wi WaitInfo) TimeToWait() time.Duration {
44         now := time.Now()
45         lib.Logger.Println("WaitInfo.TimeToWait() now: ", now)
46
47         next_time := wi.last_collected.Add(wi.collect_interval)
48         lib.Logger.Println("WaitInfo.TimeToWait() next_time: ", next_time)
49         if next_time.Before(now) {
50                 lib.Logger.Println("WaitInfo.TimeToWait() next_time scheduled time in the past, so schedule", extra_delay, "after", now)
51                 next_time = now
52                 next_time.Add(extra_delay) // add a deliberate tiny delay
53                 lib.Logger.Println("WaitInfo.TimeToWait() next_time: ", next_time, "(corrected)")
54         }
55         wait_time := next_time.Sub(now)
56         lib.Logger.Println("WaitInfo.TimeToWait() returning wait_time:", wait_time)
57
58         return wait_time
59 }
60
61 // behave like time.After()
62 func (wi WaitInfo) WaitNextPeriod() <-chan time.Time {
63         return time.After(wi.TimeToWait())
64 }