Skip to content

Commit

Permalink
ntp: Ignore setup error
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Jul 31, 2024
1 parent a2f9fef commit f97054e
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions common/ntp/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type Options struct {
Logger logger.Logger
Server M.Socksaddr
Interval time.Duration
Timeout time.Duration
WriteToSystem bool
}

Expand All @@ -39,6 +40,7 @@ type Service struct {
server M.Socksaddr
writeToSystem bool
ticker *time.Ticker
timeout time.Duration
clockOffset time.Duration
pause pause.Manager
}
Expand Down Expand Up @@ -81,16 +83,18 @@ func NewService(options Options) *Service {
writeToSystem: options.WriteToSystem,
server: destination,
ticker: time.NewTicker(interval),
timeout: options.Timeout,
pause: service.FromContext[pause.Manager](ctx),
}
}

func (s *Service) Start() error {
err := s.update()
if err != nil {
return E.Cause(err, "initialize time")
s.logger.Error(E.Cause(err, "initialize time"))
} else {
s.logger.Info("updated time: ", s.TimeFunc()().Local().Format(TimeLayout))
}
s.logger.Info("updated time: ", s.TimeFunc()().Local().Format(TimeLayout))
go s.loopUpdate()
return nil
}
Expand Down Expand Up @@ -124,23 +128,31 @@ func (s *Service) loopUpdate() {
}
err := s.update()
if err == nil {
s.logger.Debug("updated time: ", s.TimeFunc()().Local().Format(TimeLayout))
s.logger.Info("updated time: ", s.TimeFunc()().Local().Format(TimeLayout))
} else {
s.logger.Warn("update time: ", err)
s.logger.Error("update time: ", err)
}
}
}

func (s *Service) update() error {
ctx := s.ctx
var cancel context.CancelFunc
if s.timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, s.timeout)
}
response, err := Exchange(s.ctx, s.dialer, s.server)
if cancel != nil {
cancel()
}
if err != nil {
return err
}
s.clockOffset = response.ClockOffset
if s.writeToSystem {
writeErr := SetSystemTime(s.TimeFunc()())
if writeErr != nil {
s.logger.Warn("write time to system: ", writeErr)
s.logger.Error("write time to system: ", writeErr)
}
}
return nil
Expand Down

0 comments on commit f97054e

Please sign in to comment.