在特定时间实现cron

在特定时间实现cron

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

问题描述

我一直在寻找如何实现一个函数,让你在Go中的某个时间执行任务的示例,但我找不到任何东西。



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

解决方案

这是一个通用实现,可让您设置:




  • 间隔时间





  • 运行示例可以在这里找到:
    http://play.golang.org/p/xEtiMDZhXt

      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 runningRoutine(){
    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)
    }


    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:

    • interval period
    • hour to tick
    • minute to tick
    • second to tick

    A running example can be found here:http://play.golang.org/p/xEtiMDZhXt

    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 runningRoutine() {
        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)
    }
    

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

08-20 10:54