GolangNote

Golang笔记

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

Permalink

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

Go: cron 定时任务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

本文网址: https://golangnote.com/topic/107.html 转摘请注明来源

Related articles

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Write a Comment to "用go 标准库实现的简单cron 定时任务"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms