go实现定时功能两种方法
1:timer
学习自:https://studygolang.com/articles/2479
timer1 := time.NewTimer(time.Second * 2) //此处在等待channel中的信号,执行此段代码时会阻塞两秒 <-timer1.C
timer1 := time.NewTimer(time.Second * 2) //此处在等待channel中的信号,执行此段代码时会阻塞两秒 <-timer1.C ticker := time.NewTimer(time.Second) for_ =range ticker.C{ }
或者
for { select { case <-timer.C: func() } }
timer中:
type Ticker struct { C <-chan Time // The channel on which the ticks are delivered. r runtimeTimer }
C只能读不能写
https://studygolang.com/articles/4565
2:"github.com/robfig/cron"中的cron
package main
import (
"github.com/robfig/cron"
"log"
)
func main() {
i := 0
c := cron.New()
spec := "*/5 * * * * ?"
c.AddFunc(spec, func() {
i++
log.Println("cron running:", i)
})
c.AddFunc("@every 1h1m", func() {
i++
log.Println("cron running:", i)
})
c.Start()
}