Golang - 如何在特定时间执行功能 [英] Golang - How to execute function at specific times

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

问题描述

我需要在一天的特定时间运行一个函数(例如0010,0610,1210,1810)。我现在的方法是使用一个代码作为_ = range time.Tick(21600 * time.Second),我手动以这些间隔之一(例如1210)启动程序。这显然是次优的。



最佳解决方案是什么?我想每60秒运行一次ticker,然后检查时间是否匹配其中一个间隔,但这看起来不太优雅。

限制你的计划程序,以便在每个时间间隔内完成您想要完成的任务,但是使用现有的调度程序来执行调度 - 一个简单的示例是使用cron作业(或者对于Windows,Task Scheduler)根据所需的时间表启动程序


  • 将您的程序变成一个调度程序,它根据时间顺序正确调用所需的函数。理想情况下,您的程序需要作为守护程序(Windows上的服务)运行,或者启动一次并以某种方式始终运行。

  • I'm need to run a function at specific times of the day (e.g. 0010, 0610, 1210, 1810). My current approach uses a ticker for _ = range time.Tick(21600 * time.Second) and I manually launch the program at one of these intervals (e.g 1210). This is obviously sub-optimal.

    What's the best solution to this? I thought of running the ticker every 60 seconds and then checking to see if the time matched one of the intervals, but that doesn't seem very elegant.

    解决方案

    What you're really after here is a scheduler, so your options are:

    • Limit your program to just what you want done at each interval, but use an existing scheduler to do the scheduling - a simple example would be to use a cron job (or for Windows, Task Scheduler) to launch your program according to the required schedule

    • Turn your program into a scheduler in its own right, which invokes the required function correctly on schedule. Your program would then ideally need to run as a daemon (service, on Windows), or be launched once and left running all the time somehow

    这篇关于Golang - 如何在特定时间执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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