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
+10.7k Golang : Get local time and equivalent time in different time zone
+10.3k Golang : Text file editor (accept input from screen and save to file)
+24.1k Golang : Find biggest/largest number in array
+25.8k Golang : How to write CSV data to file
+19k Golang : Padding data for encryption and un-padding data for decryption
+13.1k Golang : List objects in AWS S3 bucket
+15.3k nginx: [emerg] unknown directive "ssl"
+18.9k Golang : Delete duplicate items from a slice/array
+5.3k Golang : Print instead of building pyramids
+6.3k Golang : Extract sub-strings
+6k Golang : Extract unicode string from another unicode string example
+41.1k Golang : How to check if a string contains another sub-string?