beego的toolbox模块,包括了以下几个功能:健康检查、性能调试、访问统计、计划任务。今天要了解的就是这个计划任务功能,首先你需要安装这个包,github.com/astaxie/beego/toolbox
。下面我们具体看如何使用,以一个例子演示。
package main
import (
"github.com/astaxie/beego/toolbox"
"fmt"
"time"
)
func main() {
tk := toolbox.NewTask("myTask", "0 07 13 * * *", func() error { fmt.Println("hello world"); return nil })
err := tk.Run()
if err != nil {
fmt.Println(err)
}
toolbox.AddTask("myTask", tk)
toolbox.StartTask()
time.Sleep(6 * time.Second)
toolbox.StopTask()
}
函数NewTask(func NewTask(tname string,spec string,f TaskFunc))会返回一个新的任务,它需要三个参数:tname表示任务名称,spec为任务时间描述,f为要执行的函数。
spec详解
beego中的spec设计参考Linux中cron的配置。其中前6个字段依次分别表示:秒钟:0-59、分钟:0-59、小时:1-23、日期:1-31、月份:1-12、星期:0-6(0 表示周日)