Golang : Fix go-cron set time not working issue
Problem :
You followed the go-cron example at https://pkg.go.dev/github.com/go-co-op/gocron#section-readme but later on found out that the scheduled task did not execute at the specified time.
s := gocron.NewScheduler(time.UTC)
// set time
s.Every(1).Day().At("10:30").Do(func(){ ... })
// set multiple times
s.Every(1).Day().At("10:30;08:00").Do(func(){ ... })
Solution :
Instead of using time.UTC
, set the time location first to whatever timezone your server/machine is running at and then use the time for the go-cron scheduler.
For example :
localTime, err := time.LoadLocation("Asia/Singapore")
if err != nil {
logs.Fatal().Err(err).Msg("Error in time load location")
}
cronScheduler := gocron.NewScheduler(localTime)
Hope this helps and happy coding!
See also : Golang : How to get time zone and load different time zone?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+19.4k Generate checksum for a file in Go
+8.5k Golang : How to flush a channel before the end of program?
+4.2k Golang : Dealing with backquote
+6.4k Golang : Count leading or ending zeros(any item of interest) example
+14.8k Golang : [json: cannot unmarshal object into Go value of type]
+4.9k Golang : How to call function inside template with template.FuncMap
+5.5k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+4.4k Golang : Find the shortest line of text example
+16.7k Golang : Saving private and public key to files
+10.3k Golang : Linear algebra and matrix calculation example
+11.6k Golang : Strings comparison
+4.3k PageSpeed : Clear or flush cache on web server