Golang - How to execute function at specific times

2019-06-25 21:32发布

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.

标签: time go
1条回答
看我几分像从前
2楼-- · 2019-06-25 22:20

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

查看更多
登录 后发表回答