Executing Code at Noon in Golang
In this scenario, we aim to run a specific function at noon every day while handling user input during the rest of the program's execution. Several approaches can effectively achieve this:
Interval Timer
Timer functions in Go allow us to execute tasks at predefined intervals. To schedule a function at noon daily, we can use:
Calculating the Interval
To determine the interval between the current time and the next noon, we first calculate the time remaining until the first noon after the program starts. We then use a 24-hour interval for subsequent noon tasks.
Sample Code using time.Sleep:
package main import "fmt" import "time" func noonTask() { fmt.Println(time.Now()) fmt.Println("do some job.") } func initNoon() { t := time.Now() n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location()) d := n.Sub(t) if d < 0 { n = n.Add(24 * time.Hour) d = n.Sub(t) } for { time.Sleep(d) d = 24 * time.Hour noonTask() } } func main() { initNoon() }
Using timer.AfterFunc:
package main import ( "fmt" "sync" "time" ) func noonTask() { fmt.Println(time.Now()) fmt.Println("do some job.") timer.AfterFunc(duration(), noonTask) } func main() { timer.AfterFunc(duration(), noonTask) wg.Add(1) // do normal task here wg.Wait() } func duration() time.Duration { t := time.Now() n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location()) if t.After(n) { n = n.Add(24 * time.Hour) } d := n.Sub(t) return d } var wg sync.WaitGroup
Additional Information
The above is the detailed content of How to Execute a Go Function Daily at Noon While Handling Concurrent User Input?. For more information, please follow other related articles on the PHP Chinese website!