go實現定時功能兩種方法

1:timergit

學習自:https://studygolang.com/articles/2479github

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{

}

或者golang

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"中的croncode

package mainblog

import (
"github.com/robfig/cron"
"log"
)it

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()
}class

相關文章
相關標籤/搜索