登录
首页 >  Golang >  Go问答

如何定时设置作业运行?

来源:stackoverflow

时间:2024-02-19 17:21:23 137浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《如何定时设置作业运行?》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我想每天晚上 9 点打印出 do 我的工作 。我怎样才能在 go 中做到这一点?

这是我到目前为止所得到的:

timer := time.NewTimer(3 * time.Second)
for {
    now := time.Now()
    next := now.Add(time.Hour * 24)
    todayNine := time.Date(next.Year(), next.Month(), next.Day(), 9, 0, 0, 0, next.Location()).AddDate(0, 0, -1)
    todayFifteen := time.Date(next.Year(), next.Month(), next.Day(), 15, 0, 0, 0, next.Location()).AddDate(0, 0, -1)
    todayEnd := time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location()).AddDate(0, 0,  -1)
    if now.Before(todayNine) {
        timer.Reset(todayNine.Sub(now))
    } else if now.Before(todayFifteen) {
        timer.Reset(todayFifteen.Sub(now))
    } else if now.Before(todayEnd) {
        timer.Reset(todayEnd.Sub(now))
    }
    <- timer.C
    fmt.Println("do my job")
}

解决方案


我会探索操作系统级别或基础设施级别系统来触发这些时间的执行(*nix 中的 cron 作业、k8s 中的 cron 等)

但是,如果您想纯粹使用 go 来完成此操作,您可以尝试同时使用 tickerclock

package main

import (
    "context"
    "fmt"
    "os"
    "time"
    "os/signal"
)

func main() {
    ticker := time.NewTicker(time.Minute)
    done := make(chan bool)
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()
    go func() {
        for {
            select {
            case <-done:
                return
            case <-ticker.C:
                h, m, _ := time.Now().Clock()
                if m == 0 && (  h == 9 || h == 15 ) {
                    fmt.Printf("Doing the job")
                }
            }
        }
    }()

    <-ctx.Done()
    stop()
    done <- true
}

链接到 plaground

本篇关于《如何定时设置作业运行?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>