Golang – 如何在特定时间执行函数

huangapple go评论73阅读模式
英文:

Golang - How to execute function at specific times

问题

我需要在一天的特定时间运行一个函数(例如0010、0610、1210、1810)。我目前的方法是使用一个计时器for _ = range time.Tick(21600 * time.Second),然后手动在这些时间间隔之一启动程序(例如1210)。这显然不是最佳解决方案。

有什么更好的解决方案吗?我考虑过每60秒运行一次计时器,然后检查时间是否与其中一个时间间隔匹配,但这似乎不太优雅。

英文:

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.

答案1

得分: 3

你真正需要的是一个调度器,所以你的选择有:

  • 限制你的程序只执行每个时间间隔所需的任务,但使用现有的调度器来进行调度 - 一个简单的例子是使用 cron 作业(或对于 Windows,任务计划程序)根据所需的计划启动你的程序。

  • 将你的程序变成一个独立的调度器,在预定的时间正确地调用所需的函数。你的程序最好能作为守护进程(在 Windows 上是服务)运行,或者启动一次后一直保持运行状态。

英文:

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

huangapple
  • 本文由 发表于 2015年11月15日 10:46:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/33715842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定