-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathntp.go
48 lines (40 loc) · 969 Bytes
/
ntp.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
package main
import (
"flag"
"fmt"
"time"
"github.com/beevik/ntp"
)
type NTPClient struct {
Url string
Resp ntp.Response
}
func ConnectNTP(url string) (*NTPClient, error) {
if len(url) == 0 {
return nil, fmt.Errorf("NTP URL is empty")
}
return &NTPClient{Url: url}, nil
}
func (c *NTPClient) GetOffset() int64 {
return c.Resp.ClockOffset.Nanoseconds()
}
func (c *NTPClient) SingleQuery() {
resp, err := ntp.Query(c.Url)
if err != nil {
fmt.Printf("NTP error: %v\n", err)
} else {
c.Resp = *resp
}
}
var ntpMaxPoll = flag.Duration("ntpMaxPoll", 250*time.Millisecond, "NTP Max Poll Interval")
func (c *NTPClient) QueryLoop(pred func(ntp.Response) bool) {
for pred(c.Resp) {
c.SingleQuery()
sleepDur := *ntpMaxPoll
// Poll is the maximum interval between successive NTP polling messages. It is not relevant for simple NTP clients like this one.
if c.Resp.Poll < sleepDur {
// sleepDur = c.Resp.Poll
}
time.Sleep(sleepDur)
}
}