仅当未运行时才使用 cron 运行 python 脚本 [英] Running python script with cron only if not running
问题描述
我需要每分钟运行一个 python 脚本 (job.py).如果此脚本已在运行,则不得启动该脚本.它的执行时间可以在 10 秒到几个小时之间.
I need to run a python script (job.py) every minute. This script must not be started if it is already running. Its execution time can be between 10 seconds and several hours.
所以我放入了我的 crontab:
So I put into my crontab:
* * * * * root cd /home/lorenzo/cron && python -u job.py 1>> /var/log/job/log 2>> /var/log/job/err
为了避免在脚本已经运行时启动脚本,我使用了 flock().
To avoid starting the script when it is already running, I use flock().
这是脚本(job.py):
This is the script (job.py):
import fcntl
import time
import sys
def doIncrediblyImportantThings ():
for i in range (100):
sys.stdout.write ('[%s] %d.
' % (time.strftime ('%c'), i) )
time.sleep (1)
if __name__ == '__main__':
f = open ('lock', 'w')
try: fcntl.lockf (f, fcntl.LOCK_EX | fcntl.LOCK_NB)
except:
sys.stderr.write ('[%s] Script already running.
' % time.strftime ('%c') )
sys.exit (-1)
doIncrediblyImportantThings ()
这种方法似乎有效.
有什么我遗漏的吗?使用这种方法有什么问题吗?
Is there anything I am missing? Are there any troubles I can run into using this approach?
是否有更多建议或适当"的方法来实现这种行为?
Are there more advised or "proper" ways of achieving this behaviour?
感谢您的任何建议.
推荐答案
我提出的唯一建议是让您的异常处理更具体一些.您不想有一天意外删除 fcntl
导入并隐藏结果的 NameError
.始终尝试捕获您想要处理的最具体的异常.在这种情况下,我建议如下:
The only suggestion I would make is to make your exception handling a little more specific. You don't want to accidentally delete the fcntl
import one day and hide the NameError
that results. Always try to catch the most specific exception you want to handle. In this case, I suggest something like:
import errno
try:
fcntl.lock(...)
except IOError, e:
if e.errno == errno.EAGAIN:
sys.stderr.write(...)
sys.exit(-1)
raise
这样,无法获得锁的任何其他原因都会显示出来(可能在您的电子邮件中,因为您使用的是 cron),您可以决定是否需要管理员查看,另一个原因程序处理的情况,或其他.
This way, any other cause of the lock being unobtainable shows up (probably in your email since you're using cron) and you can decide if it's something for an administrator to look at, another case for the program to handle, or something else.
这篇关于仅当未运行时才使用 cron 运行 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!