只有如果没有运行,用cron运行python脚本 [英] Running python script with cron only if not running

查看:337
本文介绍了只有如果没有运行,用cron运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要每分钟运行一个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


$ b $ p

为了避免脚本已经运行, 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.\n' % (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.\n' % 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屋!

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