Golang 定时器

Golang实现一个每二十四小时触发一次任务的定时器。代码如下:

const (
    //interval
    INTERVAL_PERIOD time.Duration = 24 * time.Hour

    //start time
    HOUR_TO_TICK   int = 00
    MINUTE_TO_TICK int = 10
    SECOND_TO_TICK int = 00
)

func main() {
    ticker := updateTicker()
    for {
        <-ticker.C
        fmt.Println("exec task here!")
        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 interval")
    diff := nextTick.Sub(time.Now())
    return time.NewTicker(diff)
}

你可能感兴趣的:(golang)