Golang实现定时器

声明

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 {}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值