Golang:在特定时间实施cron/执行任务 [英] Golang: Implementing a cron / executing tasks at a specific time

查看:32
本文介绍了Golang:在特定时间实施cron/执行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找有关如何在 Go 中实现允许您在特定时间执行任务的功能的示例,但我找不到任何东西.

I have been looking around for examples on how to implement a function that allows you to execute tasks at a certain time in Go, but I couldn't find anything.

我自己实现了一个并在答案中分享,所以其他人可以参考他们自己的实现.

I implemented one myself and I am sharing it in the answers, so other people can have a reference for their own implementation.

推荐答案

这是一个通用的实现,可以让你设置:

This is a general implementation, which lets you set:

  • 间隔期
  • 打勾的小时
  • 打勾的分钟
  • 第二个打勾

更新:(修复了内存泄漏)

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

type jobTicker struct {
    timer *time.Timer
}

func runningRoutine() {
    jobTicker := &jobTicker{}
    jobTicker.updateTimer()
    for {
        <-jobTicker.timer.C
        fmt.Println(time.Now(), "- just ticked")
        jobTicker.updateTimer()
    }
}

func (t *jobTicker) updateTimer() {
    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())
    if t.timer == nil {
        t.timer = time.NewTimer(diff)
    } else {
        t.timer.Reset(diff)
    }
}

这篇关于Golang:在特定时间实施cron/执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆