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
+5.2k Golang *File points to a file or directory ?
+23.5k Golang : Fix type interface{} has no field or no methods and type assertions example
+9.1k Golang : Terminate-stay-resident or daemonize your program?
+46k Golang : Marshal and unmarshal json.RawMessage struct example
+4.9k Golang : Customize scanner.Scanner to treat dash as part of identifier
+38.8k Golang : How to iterate over a []string(array)
+13k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+21.4k SSL : How to check if current certificate is sha1 or sha2
+9k Golang : Temperatures conversion example
+34.8k Golang : Upload and download file to/from AWS S3
+10.8k Golang : Web routing/multiplex example