Reputation: 77
I want to print out do my job
every day at 9pm. How can I do this in Go?
Here's what I've got so far:
timer := time.NewTimer(3 * time.Second)
for {
now := time.Now()
next := now.Add(time.Hour * 24)
todayNine := time.Date(next.Year(), next.Month(), next.Day(), 9, 0, 0, 0, next.Location()).AddDate(0, 0, -1)
todayFifteen := time.Date(next.Year(), next.Month(), next.Day(), 15, 0, 0, 0, next.Location()).AddDate(0, 0, -1)
todayEnd := time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location()).AddDate(0, 0, -1)
if now.Before(todayNine) {
timer.Reset(todayNine.Sub(now))
} else if now.Before(todayFifteen) {
timer.Reset(todayFifteen.Sub(now))
} else if now.Before(todayEnd) {
timer.Reset(todayEnd.Sub(now))
}
<- timer.C
fmt.Println("do my job")
}
Upvotes: 3
Views: 5010
Reputation: 7091
I would explore OS level or Infrastructure level system to trigger the execution at these times ( Cron jobs in *nix, Cron in k8s etc.)
However, If you want to do it using purely go
you may try using the ticker
and Clock
together
package main
import (
"context"
"fmt"
"os"
"time"
"os/signal"
)
func main() {
ticker := time.NewTicker(time.Minute)
done := make(chan bool)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
go func() {
for {
select {
case <-done:
return
case <-ticker.C:
h, m, _ := time.Now().Clock()
if m == 0 && ( h == 9 || h == 15 ) {
fmt.Printf("Doing the job")
}
}
}
}()
<-ctx.Done()
stop()
done <- true
}
Link to the plaground
Upvotes: 4
Reputation: 676
I would use cron
package. https://pkg.go.dev/github.com/robfig/cron
Example from documentation:
c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.AddFunc("@hourly", func() { fmt.Println("Every hour") })
c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.Start()
..
// Funcs are invoked in their own goroutine, asynchronously.
...
// Funcs may also be added to a running Cron
c.AddFunc("@daily", func() { fmt.Println("Every day") })
..
// Inspect the cron job entries' next and previous run times.
inspect(c.Entries())
..
c.Stop() // Stop the scheduler (does not stop any jobs already running).
Upvotes: 2