当前位置:网站首页>Timers in golang

Timers in golang

2022-06-12 10:23:00 love666666shen

stay golang In the program , have access to crontab Time task processing , It can also be done through Timer or Ticker Simply set the scheduled task .

Timer and Ticker The difference between timers is :
Use Timer When timer , Need to call Reset Method to reset the timer event ; and Ticker Timing does not need to call Reset.

Timer Examples of timed tasks :

func process() {
    
	interval := 6 * time.Second
	timer := time.NewTimer(interval)
	ctx, _ := context.WithTimeout(ctx, 2 * time.Second)
	//  Timed task processing logic 
	processLogic()
	for {
    
		//  call Reset Method pair timer Object to reset the timer 
		timer.Reset(interval)
		select {
    
		case <-ctx.Done():
			//  timeout handler 
			log.Info("process timeout, exit")
			return
		case <-timer.C:
			//  Timed task processing logic 
			processLogic()
		}
	}
}

Ticker Timing task , Unwanted Reset Reset timer .Ticker Examples of scheduled tasks are as follows :

......
ticker := time.NewTicker(time.Second)
ctx, _ := context.WithTimeout(ctx, 2 * time.Second)
for {
    
	select {
    
	case <-ticker.C:
		//  Timed task processing logic 
		...
	case <-ctx.Done():
		fmt.Println("request timeout")
		//  End the scheduled task 
		return
	}
}
......
原网站

版权声明
本文为[love666666shen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121018333833.html