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
+4.5k PHP : Extract part of a string starting from the middle
+11k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+19.5k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+13.9k Golang : Get uploaded file name or access uploaded files
+11.4k How to tell if a binary(executable) file or web application is built with Golang?
+11.1k Golang : Byte format example
+8.6k Golang : GMail API create and send draft with simple upload attachment example
+21.3k Golang : Convert string slice to struct and access with reflect example
+12.6k Python : Convert IPv6 address to decimal and back to IPv6
+4.6k Which content-type(MIME type) to use for JSON data
+6.3k Golang : Totalize or add-up an array or slice example
+5.3k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)