beego.toolbox的定时任务的使用

参考文章:http://beego.top/example/toolbox.html#task

beego里的toolbox.StartTask()是有协程go出去,所以需要加个协程锁,保证子协程能执行完。

package main

import (
    "sync"
    "time"

    "github.com/astaxie/beego/logs"
    "github.com/astaxie/beego/toolbox"
)

var TimerWg sync.WaitGroup

func generateWarning() error {
    defer TimerWg.Done()
    logs.Error("hello time:%v", time.Now())
    return nil
}

func main() {
    TimerWg = sync.WaitGroup{}
    TimerWg.Add(1)
    logs.Debug("start :%v", time.Now())
    tk := toolbox.NewTask("generateWarning", "0 59 17 * * *", generateWarning)
    toolbox.AddTask("generateWarning", tk)
    toolbox.StartTask()
    logs.Debug("StartTask :%v", time.Now())
    defer toolbox.StopTask()
    TimerWg.Wait()
    logs.Debug("Wait :%v", time.Now())

}

输出:

ev@dev-VirtualBox test (master) $ go run beegotest/test_toolbox.go 
2020/09/28 17:58:22.945 [D]  start :2020-09-28 17:58:22.945124454 +0800 CST m=+0.000350274
2020/09/28 17:58:22.945 [D]  StartTask :2020-09-28 17:58:22.945457098 +0800 CST m=+0.000682916
2020/09/28 17:59:00.001 [E]  hello time:2020-09-28 17:59:00.001469156 +0800 CST m=+37.056695119
2020/09/28 17:59:00.001 [D]  Wait :2020-09-28 17:59:00.001670887 +0800 CST m=+37.056896833

你可能感兴趣的:(beego.toolbox的定时任务的使用)