golang中的定时器

贺宝
2023-12-01

在golang程序中,可以使用crontab进行定时任务处理,也可以通过Timer或Ticker简单地进行定时任务设置。

Timer和Ticker定时器的区别为:
使用Timer定时器时,需要调用Reset方法对定时器事件进行重置;而Ticker定时不需要调用Reset。

Timer定时任务示例:

func process() {
	interval := 6 * time.Second
	timer := time.NewTimer(interval)
	ctx, _ := context.WithTimeout(ctx, 2 * time.Second)
	// 定时任务处理逻辑
	processLogic()
	for {
		// 调用Reset方法对timer对象进行定时器重置
		timer.Reset(interval)
		select {
		case <-ctx.Done():
			// 超时处理
			log.Info("process timeout, exit")
			return
		case <-timer.C:
			// 定时任务处理逻辑
			processLogic()
		}
	}
}

Ticker定时任务,不需要Reset重置定时器。Ticker定时任务示例如下:

......
ticker := time.NewTicker(time.Second)
ctx, _ := context.WithTimeout(ctx, 2 * time.Second)
for {
	select {
	case <-ticker.C:
		// 定时任务处理逻辑
		...
	case <-ctx.Done():
		fmt.Println("request timeout")
		// 结束定时任务
		return
	}
}
......
 类似资料: