Golang : How to execute code at certain day, hour and minute?
Problem:
You want to execute certain code at a particular day, hour and minute only. Such as Monday, 10:30 AM. How to do that?
Solution:
Normally, this should be solved with cron
or scheduler
utility. However, no harm knowing how to do it at code level.
You will need time.Now()
, time.Clock()
and time.Weekday()
to retrieve the current day, hour, minute and second to determine if the condition is right to execute your code.
Here you go!
package main
import (
"fmt"
"os"
"time"
)
func main() {
now := time.Now()
day := now.Weekday()
hr, min, sec := now.Clock()
// only execute code on Monday 10:30 AM
fmt.Println("Code will only execute on every Monday, 10:30 AM")
// ignore second for now
if day == 1 && hr == 10 && min == 30 {
fmt.Println("Executing this portion of code to cure Monday blues...")
} else {
fmt.Printf("However, it is [%v], [%d]hour : [%d]minutes : [%d] seconds now.\n", day.String(), hr, min, sec)
fmt.Println("So, go back to work!")
os.Exit(0)
}
}
If the program runs on Monday 10:30AM, the output will be:
$ ./particularday
Code will only execute on every Monday, 10:30 AM
Executing this portion of code to cure Monday blues...
else the output will be:
Code will only execute on every Monday, 10:30 AM
However, it is [Monday], [10]hour : [46]minutes : [51] seconds now.
So, go back to work!
References:
https://www.socketloop.com/references/golang-time-time-clock-function-example
https://www.socketloop.com/tutorials/golang-how-to-get-year-month-and-day
See also : Golang : How to get year, month and day?
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
+29.5k Golang : Get and Set User-Agent examples
+15.3k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+18.4k Golang : Generate thumbnails from images
+8.9k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+4.8k Golang : Constant and variable names in native language
+6.9k Golang : A simple forex opportunities scanner
+8k Golang : Emulate NumPy way of creating matrix example
+17.3k Golang : Find smallest number in array
+30.6k Golang : Interpolating or substituting variables in string examples
+33.7k Golang : Call a function after some delay(time.Sleep and Tick)
+9.6k Golang : ffmpeg with os/exec.Command() returns non-zero status
+7.2k Golang : Check to see if *File is a file or directory