1.定时器创建与停止

//定时器使用
	t1 := time.NewTimer(2 * time.Second)
	<-t1.C
	fmt.Println("timer1 fired")
	t2 := time.NewTimer(5 * time.Second)
	go func() {
		fmt.Println("go协程处理中,等待5秒后输出...")
		<-t2.C
		fmt.Println("timer2 fired")
	}()
	fmt.Println("主线程等待10秒...")
	t2Stop := t2.Stop() //停止定时器
	if t2Stop {
		fmt.Println("t2定时器已停止...", t2Stop)
	}
	time.Sleep(time.Second * 10)
	fmt.Println("完成")

输出:

timer1 fired
主线程等待10秒...
t2定时器已停止... true
go协程处理中,等待5秒后输出...
完成

2.定时器配合协程使用

tick := time.NewTicker(500 * time.Millisecond) //500毫秒
	timeEnd := make(chan bool)                     //结束通道
	//协程
	go func() {
		//循环
		for {
			//随机执行任务
			select {
			case <-timeEnd: //结束任务
				fmt.Println("===结束任务")
				return
			case t := <-tick.C: //超时任务
				fmt.Println("==500毫秒响应一次:", t)
			}
		}
	}()
	time.Sleep(5000 * time.Millisecond) //休眠5秒
	tick.Stop()                         //停止定时器
	timeEnd <- true                     //设置结束标志
	fmt.Println("===定时任务结束===")

输出:

==500毫秒响应一次: 2024-06-07 11:27:28.4894537 +0800 CST m=+17.528309301
==500毫秒响应一次: 2024-06-07 11:27:28.9967727 +0800 CST m=+18.035628301
==500毫秒响应一次: 2024-06-07 11:27:29.4893206 +0800 CST m=+18.528176201
==500毫秒响应一次: 2024-06-07 11:27:29.9896915 +0800 CST m=+19.028547101
==500毫秒响应一次: 2024-06-07 11:27:30.4901046 +0800 CST m=+19.528960201
==500毫秒响应一次: 2024-06-07 11:27:30.9907067 +0800 CST m=+20.029562301
==500毫秒响应一次: 2024-06-07 11:27:31.4951615 +0800 CST m=+20.534017101
==500毫秒响应一次: 2024-06-07 11:27:32.0016405 +0800 CST m=+21.040496101
==500毫秒响应一次: 2024-06-07 11:27:32.497787 +0800 CST m=+21.536642601
==500毫秒响应一次: 2024-06-07 11:27:32.9988599 +0800 CST m=+22.037715501
===结束任务
===定时任务结束===