From 2d65f565ec2ec3eef2bfdaeb7ff30c3a814ddc70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=90=99PiperYxzzy?= Date: Sun, 29 May 2022 20:10:03 +0200 Subject: [PATCH] Updated scheduling package for more flexibility --- main.go | 2 +- scheduled/scheduled.go | 16 +++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index 1c33261..4368d5f 100644 --- a/main.go +++ b/main.go @@ -33,7 +33,7 @@ func main() { Migrate(db) // Scheduled tasks - scheduled.Schedule(func() (string, time.Duration) { + go scheduled.ExecuteImmediatelyAndSchedule(func() (string, time.Duration) { err := database.Db.Where("used < ?", time.Now().Add(-24*time.Hour)).Delete(&models.TotpUsage{}).Error if err != nil { return "purge failed, trying again in one hour: " + err.Error(), time.Hour diff --git a/scheduled/scheduled.go b/scheduled/scheduled.go index 76728a8..1665d20 100644 --- a/scheduled/scheduled.go +++ b/scheduled/scheduled.go @@ -7,12 +7,18 @@ import ( type Scheduled func() (string, time.Duration) -func Schedule(f Scheduled) { +func ExecuteImmediatelyAndSchedule(f Scheduled) { print, wait := f() fmt.Println(print) - go func(w time.Duration) { - time.Sleep(w) - Schedule(f) - }(wait) + go ExecuteWithDelayAndSchedule(f, wait) +} + +func ExecuteWithDelayAndSchedule(f Scheduled, wait time.Duration) { + time.Sleep(wait) + + print, nextWait := f() + fmt.Println(print) + + go ExecuteWithDelayAndSchedule(f, nextWait) }