Golang笔记

用go 标准库实现的简单cron 定时任务

go 标准库实现的简单cron 定时任务

package main

import (
    "fmt"
    "time"
)

const INTERVAL_PERIOD time.Duration = 24 * time.Hour

const HOUR_TO_TICK int = 23
const MINUTE_TO_TICK int = 00
const SECOND_TO_TICK int = 03

func main() {
    ticker := updateTicker()
    for {
    <-ticker.C
    fmt.Println(time.Now(), "- just ticked")
    ticker = updateTicker()
    }
}

func updateTicker() *time.Ticker {
    nextTick := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), HOUR_TO_TICK, MINUTE_TO_TICK, SECOND_TO_TICK, 0, time.Local)
    if !nextTick.After(time.Now()) {
        nextTick = nextTick.Add(INTERVAL_PERIOD)
    }
    fmt.Println(nextTick, "- next tick")
    diff := nextTick.Sub(time.Now())
    return time.NewTicker(diff)
}

以上代码实现一天运行一次的任务,更复杂的可以使用简单的库 gocron https://github.com/jasonlvhit/gocron 368

本文网址: https://golangnote.com/topic/107.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles