time.go 1.2 KB
Newer Older
Lei Li's avatar
Lei Li committed
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
package time

import (
	"syscall"
	"time"

	"linkfog.com/public/lib/l"

	"github.com/beevik/ntp"
)

func SynchronizeSystemTime() bool {
	l.Info("the current device start check time sync...")
	defer l.Info("sync system time ends")

	go func() {
		pool := make([]string, 0)
		pool = append(pool, "pool.ntp.org")
		pool = append(pool, "cn.pool.ntp.org")
		pool = append(pool, "ntp1.aliyun.com")
		pool = append(pool, "ntp.ntsc.ac.cn")
		pool = append(pool, "time1.cloud.tencent.com")
		pool = append(pool, "time.ustc.edu.cn")

		for _, v := range pool {
			response, err := ntp.Query(v)
			if err != nil {
				l.Warn("Failed to get time from NTP:", err)
				continue
			}

			ntpTime := time.Now().Add(response.ClockOffset)
			tv := syscall.NsecToTimeval(ntpTime.UnixNano())
			err = syscall.Settimeofday(&tv)
			if err != nil {
				l.Warnf("Failed to set system time: %v", err)
				continue
			} else {
				l.Info("set system time successfully")
				break
			}
		}
	}()

	for i := 30; i > 0; i-- {
		ts := time.Now().Unix()
		//2024-04-01 00:00:00
		if ts > 1711900800 {
			l.Info("time sync success...", ts)
			return true
		} else {
			l.Warn("time does not sync...", ts)
		}
		time.Sleep(10 * time.Second)
	}
	return false
}