From 5b3e0c8074cbe2131b8b93e7c292d743db35e9ef Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Wed, 29 Jan 2025 11:23:16 +0800 Subject: [PATCH] refactor: periodic operations to use `time.Ticker` (#978) - Use `time.Ticker` instead of `time.After` for periodic operations in `autoSave` function - Use `time.Ticker` instead of `time.After` for periodic operations in `monitor` function Signed-off-by: appleboy --- storage/store/store.go | 4 +++- watchdog/watchdog.go | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/storage/store/store.go b/storage/store/store.go index 772c3ce0..729e6482 100644 --- a/storage/store/store.go +++ b/storage/store/store.go @@ -133,12 +133,14 @@ func Initialize(cfg *storage.Config) error { // autoSave automatically calls the Save function of the provider at every interval func autoSave(ctx context.Context, store Store, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() for { select { case <-ctx.Done(): logr.Info("[store.autoSave] Stopping active job") return - case <-time.After(interval): + case <-ticker.C: logr.Info("[store.autoSave] Saving") if err := store.Save(); err != nil { logr.Errorf("[store.autoSave] Save failed: %s", err.Error()) diff --git a/watchdog/watchdog.go b/watchdog/watchdog.go index 36b0149c..38c373bc 100644 --- a/watchdog/watchdog.go +++ b/watchdog/watchdog.go @@ -41,12 +41,14 @@ func monitor(ep *endpoint.Endpoint, alertingConfig *alerting.Config, maintenance // Run it immediately on start execute(ep, alertingConfig, maintenanceConfig, connectivityConfig, disableMonitoringLock, enabledMetrics) // Loop for the next executions + ticker := time.NewTicker(ep.Interval) + defer ticker.Stop() for { select { case <-ctx.Done(): logr.Warnf("[watchdog.monitor] Canceling current execution of group=%s; endpoint=%s; key=%s", ep.Group, ep.Name, ep.Key()) return - case <-time.After(ep.Interval): + case <-ticker.C: execute(ep, alertingConfig, maintenanceConfig, connectivityConfig, disableMonitoringLock, enabledMetrics) } }