一、Timer定时器
1.Timer定时器框架实现
package main
import (
"fmt"
"time"
)
func main () {
d := time.Duration(time.Second * 2)
t := time.NewTimer(d)
go func() {
for {
<- t.C
fmt.Println("Timer task is working")
t.Reset(time.Second * 2)
}
}()
for {
fmt.Println("main is running:")
time.Sleep(time.Duration(1 * time.Second))
}
defer t.Stop()
}
二、Ticker定时器
1.Ticker定时器框架实现
package main
import (
"fmt"
"time"
)
func main () {
d := time.Duration(time.Second * 2)
t := time.NewTicker(d)
go func() {
for {
<- t.C
fmt.Println("Timer task is working")
}
}()
for {
fmt.Println("main is running:")
time.Sleep(time.Duration(1 * time.Second))
}
defer t.Stop()
}
三、Timer和Ticker的差异
1.Timer到时间需要Reset重置,而Ticker不需要,每到间隔时间就会执行任务处理函数
//如果Timer定时器不使用Reset,就只执行了一次任务
package main
import (
"fmt"
"time"
)
func main () {
d := time.Duration(time.Second * 2)
t := time.NewTimer(d)
go func() {
for {
<- t.C
fmt.Println("Timer task is working")
//t.Reset(time.Second * 2)
}
}()
for {
fmt.Println("main is running:")
time.Sleep(time.Duration(1 * time.Second))
}
defer t.Stop()
}
四、参考资料
my.oschina.net/renhc/blog/… blog.csdn.net/lanyang1234… draveness.me/golang/docs…