Go Timer Tasks Implementation
In the Go language, you can use the time package in the standard library to implement timer tasks. Here is a simple example:
package main
import (
"fmt"
"time"
)
func main() {
// 创建一个定时器,每隔1秒触发一次
ticker := time.NewTicker(1 * time.Second)
// 使用一个goroutine来执行定时任务
go func() {
for {
select {
case <-ticker.C:
// 定时任务逻辑
fmt.Println("定时任务执行:", time.Now())
}
}
}()
// 程序将持续运行10秒
time.Sleep(10 * time.Second)
// 停止定时器
ticker.Stop()
fmt.Println("定时任务已停止")
}
In this example, a timer that triggers every 1 second was created using time.NewTicker, and a goroutine was used to execute the timed task logic. The program will run for 10 seconds before calling ticker.Stop() to stop the timer.
In this way, it is easy to implement the logic of scheduled tasks and control the start and stop of the timer.