声明
1)该文章整理自网上的大牛和专家无私奉献的资料,具体引用的资料请看参考文献。
2)本文仅供学术交流,非商用。如果某部分不小心侵犯了大家的利益,还望海涵,并联系博主删除。
3)博主才疏学浅,文中如有不当之处,请各位指出,共同进步,谢谢。
4)此属于第一版本,若有错误,还需继续修正与增删。还望大家多多指点。大家都共享一点点,一起为祖国科研的推进添砖加瓦。
源码解析
// Common durations. There is no definition for units of Day or larger
// to avoid confusion across daylight savings time zone transitions.
//
// To count the number of units in a Duration, divide:
// second := time.Second
// fmt.Print(int64(second/time.Millisecond)) // prints 1000
//
// To convert an integer number of units to a Duration, multiply:
// seconds := 10
// fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
//
//源码定义了时间
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond--秒
Minute = 60 * Second --分钟
Hour = 60 * Minute --小时
)
定时任务代码
package controller
import (
"fmt"
"time"
)
//golang自带的定时调用
func Crontab() {
for {
now := time.Now()
// 计算下一个零点
next := now.Add(time.Hour * 25)//这里定义执行时间的周期
t := time.NewTimer(next.Sub(now))
fmt.Println("当前时间为:", t)
fmt.Println("当前时间为:", next)
select {
case <-t.C:
RestTimingTask() //这里放具体实现方法
}
}
}
//在main文件中 run方法里放入定时任务方法
func run() {
runtime.GOMAXPROCS(conf.Conf.MaxProc)
/*HTTP初始化*/
if err = InitHTTP(); err != nil {
fmt.Printf("InitHTTP error! err = %v", err)
panic(err)
}
logger.Infof("InitHTTP success!\n")
go controller.Crontab()
go controller.CrontabMail() //这里放定时任务方法
c := signal.InitSignal()
signal.HandleSignal(c)
os.Exit(0)
}
// 周期性任务
func CrontabMail() {
c := cron.New()
// 每天凌晨两点执行
spec := "0 0 2 * * ?"
c.AddFunc(spec, func() {
RestTimingMail()
})
c.Start()
select {}
}