Fix markup
[pstop.git] / wait_info / wait_info.go
1 // github.com/sjmudd/wait_info - routines for managing when we
2 // collect information from MySQL.
3 package wait_info
4
5 import (
6         "github.com/sjmudd/pstop/lib"
7         "time"
8 )
9
10 // over-schedule the next wait by this time _iff__ the last scheduled time is in the past.
11 const extra_delay = 200 * time.Millisecond
12
13 // used to record when we need to collect information from MySQL
14 type WaitInfo struct {
15         last_collected   time.Time
16         collect_interval time.Duration
17 }
18
19 // returns the configured wait interval between collecting data.
20 func (wi *WaitInfo) WaitInterval() time.Duration {
21         return wi.collect_interval
22 }
23
24 // record we have just collected data now.
25 func (wi *WaitInfo) CollectedNow() {
26         wi.SetCollected(time.Now())
27 }
28
29 // Change the desired collection interval to a new value
30 func (wi *WaitInfo) SetWaitInterval(required_interval time.Duration) {
31         wi.collect_interval = required_interval
32 }
33
34 // Set the time we last collected information
35 func (wi *WaitInfo) SetCollected(collect_time time.Time) {
36         wi.last_collected = collect_time
37         lib.Logger.Println("WaitInfo.SetCollected() last_collected=", wi.last_collected)
38 }
39
40 // Return when we last collection happened
41 func (wi WaitInfo) LastCollected() time.Time {
42         return wi.last_collected
43 }
44
45 // return the amount of time to wait before doing the next collection
46 func (wi WaitInfo) TimeToWait() time.Duration {
47         now := time.Now()
48         lib.Logger.Println("WaitInfo.TimeToWait() now: ", now)
49
50         next_time := wi.last_collected.Add(wi.collect_interval)
51         lib.Logger.Println("WaitInfo.TimeToWait() next_time: ", next_time)
52         if next_time.Before(now) {
53                 lib.Logger.Println("WaitInfo.TimeToWait() next_time scheduled time in the past, so schedule", extra_delay, "after", now)
54                 next_time = now
55                 next_time.Add(extra_delay) // add a deliberate tiny delay
56                 lib.Logger.Println("WaitInfo.TimeToWait() next_time: ", next_time, "(corrected)")
57         }
58         wait_time := next_time.Sub(now)
59         lib.Logger.Println("WaitInfo.TimeToWait() returning wait_time:", wait_time)
60
61         return wait_time
62 }
63
64 // return a channel which will be written to at the next 'scheduled' time.
65 func (wi WaitInfo) WaitNextPeriod() <-chan time.Time {
66         return time.After(wi.TimeToWait())
67 }