fix: ntp service panic

This commit is contained in:
wwqgtxx 2023-09-02 12:37:43 +08:00
parent cbdf33c42c
commit a366e9a4b5
2 changed files with 21 additions and 10 deletions

View File

@ -21,7 +21,7 @@ func TestSplitArgs(t *testing.T) {
func TestExecCmd(t *testing.T) { func TestExecCmd(t *testing.T) {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
_, err := ExecCmd("dir") _, err := ExecCmd("cmd -c 'dir'")
assert.Nil(t, err) assert.Nil(t, err)
return return
} }

View File

@ -17,7 +17,7 @@ type Service struct {
ticker *time.Ticker ticker *time.Ticker
ctx context.Context ctx context.Context
cancel context.CancelFunc cancel context.CancelFunc
mu *sync.Mutex mu sync.Mutex
running bool running bool
} }
@ -26,7 +26,7 @@ func ReCreateNTPService(addr string, interval time.Duration) {
service.Stop() service.Stop()
} }
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
service = &Service{addr: addr, interval: interval, ctx: ctx, cancel: cancel, mu: &sync.Mutex{}} service = &Service{addr: addr, interval: interval, ctx: ctx, cancel: cancel}
service.Start() service.Start()
} }
@ -40,7 +40,7 @@ func (srv *Service) Start() {
for { for {
err := srv.updateTime(srv.addr) err := srv.updateTime(srv.addr)
if err != nil { if err != nil {
log.Warnln("updateTime failed:", err) log.Warnln("updateTime failed: %s", err)
} }
select { select {
case <-srv.ticker.C: case <-srv.ticker.C:
@ -54,9 +54,20 @@ func (srv *Service) Start() {
func (srv *Service) Stop() { func (srv *Service) Stop() {
srv.mu.Lock() srv.mu.Lock()
defer srv.mu.Unlock() defer srv.mu.Unlock()
srv.ticker.Stop() if service.running {
srv.cancel() srv.ticker.Stop()
service.running = false srv.cancel()
service.running = false
}
}
func (srv *Service) Running() bool {
if srv == nil {
return false
}
srv.mu.Lock()
defer srv.mu.Unlock()
return srv.running
} }
func (srv *Service) updateTime(addr string) error { func (srv *Service) updateTime(addr string) error {
@ -68,16 +79,16 @@ func (srv *Service) updateTime(addr string) error {
ntpTime := response.Time ntpTime := response.Time
offset = localTime.Sub(ntpTime) offset = localTime.Sub(ntpTime)
if offset > time.Duration(0) { if offset > time.Duration(0) {
log.Warnln("System clock is ahead of NTP time by", offset) log.Warnln("System clock is ahead of NTP time by %s", offset)
} else if offset < time.Duration(0) { } else if offset < time.Duration(0) {
log.Warnln("System clock is behind NTP time by", -offset) log.Warnln("System clock is behind NTP time by %s", -offset)
} }
return nil return nil
} }
func Now() time.Time { func Now() time.Time {
now := time.Now() now := time.Now()
if service.running && offset.Abs() > 0 { if service.Running() && offset.Abs() > 0 {
now = now.Add(offset) now = now.Add(offset)
} }
return now return now