Golang周期任务、定时任务及第三方库
时间:2018-08-17 07:44:52 +0800 CST 浏览:3678

time库实现倒计时执行、周期任务,第三方库实现Linux crontab计划任务

golang.jpg

倒计时

//主线程阻塞
timer1:=time.NewTimer(time.Second*5)
<-timer1.C
println("test")
//主线程不阻塞
    timer2 := time.NewTimer(time.Second)
    go func() {
        //等触发时的信号
        <-timer2.C
        fmt.Println("Timer 2 expired")
    }()
    //由于上面的等待信号是在新线程中,所以代码会继续往下执行,停掉计时器
    time.Sleep(time.Second*5)

高级倒计时

//golang 定时器,启动的时候执行一次,以后每天晚上12点执行
func startTimer(f func()) {
        go func() {
            for {
                f()
                now := time.Now()
                // 计算下一个零点
                next := now.Add(time.Hour * 24)
                next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
                t := time.NewTimer(next.Sub(now))
                <-t.C
            }
        }()
    }

周期任务

5秒钟后执行一个任务ticker.C是一个缓冲为1的channel,

ticker:=time.NewTicker(time.Second*5)
    go func() {
        for _=range ticker.C {
            println("test")
        }
    }()
time.Sleep(time.Minute)

第三方库

https://github.com/robfig/cron

package main

import (
    "fmt"

    "github.com/robfig/cron"
)

func main() {
    spec := "0, 40, 6, *, *, *" // 每天6:40
    c := cron.New()
    c.AddFunc(spec, yourFunc)
    c.Start()
    select {}
}

func yourFunc() {
    fmt.Println("yourFunc come here.")
}

// 每天6:40就会调用一次yourFunc函数


如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。

本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。


来说两句吧