如何每两分钟运行一次 cron 作业
我必须在我的托管提供商上设置一个 cron 作业。
这个 cron 作业需要每秒运行一次。不是很深入,只是做一下检查。
然而,托管提供商只允许 cron 作业每两分钟运行一次。 (顺便说一句,无法更改托管)
所以,我不知道如何解决这个问题?
到目前为止我的想法: 如果它只能每两分钟运行一次,我需要让它每秒运行两分钟。 1)如何让我的脚本运行两分钟,每秒执行一个函数?
但重要的是不要受到干扰。 2)我必须确保它顺利运行并保持持续活跃。
也许我也可以尝试让它永远运行,并每两分钟运行一次 cron 作业,检查它是否正在运行? 3)这可能吗?
我的朋友提到使用多线程来确保它每秒都在运行。 4)对此有何评论?
感谢您的任何建议。我用的是采埃孚。
I have to set up a cron job on my hosting provider.
This cron job needs to run every second. It's not intensive, just doing a check.
The hosting provider however only allows cron jobs to be run every two minutes. (can't change hosting btw)
So, I'm clueless on how to go about this?
My thoughts so far:
If it can only run every two minutes, I need to make it run every second for two minutes. 1) How do I make my script run for two minutes executing a function every second?
But it's important that there are no interruptions. 2) I have to ensure that it runs smoothly and that it remains constantly active.
Maybe I can also try making it run forever, and run the cron job every two minutes checking whether it is running? 3) Is this possible?
My friend mentioned using multithreading to ensure it's running every second. 4) any comments on this?
Thanks for any advice. I'm using ZF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法#3 是标准解决方案。例如,您可以让 cron 作业在每次运行时都接触一个文件。然后在启动时,您可以检查该文件最近是否被触及,如果有则立即退出。否则开始跑步。 (其他方法包括使用文件锁定,或者将 pid 写入文件并在启动时检查该 pid 是否存在并且是预期的程序。)
至于一秒超时,我建议在查询结束时调用 usleep,提供从现在到您下次想要运行的毫秒数。如果你有规律的睡眠,那么你实际上每秒跑的次数会少于一次,因为睡眠有时持续的时间比预期的要长,而且你的检查需要时间。只要您的检查运行时间不到一秒钟,就应该可以正常工作。
Approach #3 is the standard solution. For instance you can have the cron job touch a file every time it runs. Then on startup you can check whether that file has been touched recently, and if it has then exit immediately. Else start running. (Other approaches include using file locking, or else writing the pid to a file and on startup check whether that pid exists and is the expected program.)
As for the one second timeout, I would suggest calling usleep at the end of your query, supplying the number of milliseconds from now to when you next want to run. If you do a regular sleep then you'll actually run less than once a second because sleeps sometimes last longer than expected, and your check takes time. As long as your check takes under a second to run, this should work fine.
我不认为 cron 允许二级分辨率。 http://unixhelp.ed.ac.uk/CGI/man-cgi ?crontab+5
因此,即使您的托管提供商允许您也不能运行每秒重复的进程。但是,您可以使用诸如
watch
之类的用户命令来重复执行脚本。请参阅此处I don't think cron allows second level resolution. http://unixhelp.ed.ac.uk/CGI/man-cgi?crontab+5
So, even if your hosting provider allows you can't run a process that repeats every second. However, you can user command something like
watch
for repeated execution of your script. see here