The Timer of the standard library allows users to customize the timeout logic (applicable to a single channel read and write timeout, select to handle multiple channel timeouts, etc.).
- Note: Timer is a one-time trigger, which is different from Ticker, which is triggered at a certain time interval (similar to the difference between settimeout and setinterval in JavaScript).
The common way to create a Timer is as follows:
- t := time.NewTimer(d)
- t := time.AfterFunc(d, f)
- c := time.After(d)
(Note: d stands for timing; f stands for triggered action; c stands for chanel)
time.NewTimer
A practical example to illustrate the usage of this API:
package main
import (
"fmt"
"time"
)
func main() {
timer := time.NewTimer(3 * time.Second)
fmt.Printf("%T\n", timer)
//打印一下系统的当前时间
fmt.Println(time.Now())
//此处等待chanel中的数值 会阻塞3s
ch2 := timer.C
fmt.Println(<-ch2)
}
The results are as follows:
*time.Timer
2022-05-27 18:15:59.740761 +0800 CST m=+0.000224834
2022-05-27 18:16:02.741175 +0800 CST m=+3.000731959
In addition, we can cancel the timer before the timer expires, such as the following code example:
package main
import (
"fmt"
"time"
)
func main() {
// 新建一个计时器
timer2 := time.NewTimer(5 * time.Second)
//开始协程处理触发后的事件
go func() {
<-timer2.C
fmt.Println("timer2 has been completed")
}()
time.Sleep(3 * time.Second)
flag := timer2.Stop()
if flag {
fmt.Println("Timer2 was stopped")
}
}
The result of running is:
Timer2 was stopped
time.After()
It is essentially NewTimer(d).C, the function is to return to channel C after the duration d, and the time after d is stored in C.
func After(d Duration) <- chan Time
Note: If efficiency issues need to be considered, the official documentation recommends using NewTimer instead. If the current timer is no longer needed, it can also be stopped with Stop().
Reference: bilibili
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。