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.3k Golang : How to flush a channel before the end of program?
+7.6k Golang : Gaussian blur on image and camera video feed examples
+19.9k Golang : Convert string slice to struct and access with reflect example
+5.1k PageSpeed : Clear or flush cache on web server
+14.2k Golang : Get current time from the Internet time server(ntp) example
+8k Golang : Serving HTTP and Websocket from different ports in a program example
+5.7k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+7.5k Golang : How to capture return values from goroutines?
+50.5k Golang : How to get time in milliseconds?
+13.9k Golang : Find location by IP address and display with Google Map
+10.5k Golang : Get remaining text such as id or filename after last segment in URL path
+81.3k Golang : How to convert character to ASCII and back