我正在寻找最佳实践,以确保 cron 作业每分钟执行的脚本只有一个正在运行的实例。例如如果我有一个每分钟执行一次的 cron,并且如果该过程花费的时间超过一分钟,那么在完成之前不要执行另一个。
现在我有以下功能。本质上,我获取当前进程的名称,然后执行 ps grep 来查看是否列出了当前进程的计数。有点困惑,所以我正在寻找一种更Pythonic 的方式。
我将代码放在文件顶部。它确实有效,但又很困惑。
def doRunCount(stop=False,min_run=1):
import inspect
current_file = inspect.getfile( inspect.currentframe() )
print current_file
fn = current_file.split()
run_check = os.popen('ps aux | grep python').read().strip().split('\n')
run_count = 0
for i in run_check:
if i.find('/bin/sh')<0:
if i.find(current_file)>=0:
run_count = run_count + 1
if run_count>min_run:
print 'max proccess already running'
exit()
return run_count
最佳答案
我不知道您是否可以将此描述为最佳实践,但我会使用 pid 文件。下面是一个类似于我多次使用的代码片段,以确保特定应用程序只有一个实例正在运行。
import os, sys
PID_FILE = '/path/to/somewhere.pid'
if os.path.exists( PID_FILE ):
pid = int(open( PID_FILE,'rb').read().rstrip('\n'))
if len(os.popen('ps %i' % pid).read().split('\n')) > 2:
print "Already Running as pid: %i" % pid
sys.exit(1)
# If we get here, we know that the app is not running so we can start a new one...
pf = open(PID_FILE,'wb')
pf.write('%i\n' % os.getpid())
pf.close()
if __name__ == '__main__':
#Do something here!
pass
就像我说的,这与我使用过的类似,但我只是重新编写了这段代码,使其更加优雅。但它应该能够传达一般概念!希望这会有所帮助。
这里有一个轻微的修改,应该可以解决因进程崩溃而引起的任何问题。 此代码不仅会验证 pid 文件是否存在,还会验证文件中的 pid 仍然存在,并且 pid 仍然是相同的可执行文件。
import os, sys
PID_FILE = '/path/to/somewhere.pid'
if os.path.exists( PID_FILE ):
pid = int(open( PID_FILE,'rb').read().rstrip('\n'))
pinfo = os.popen('ps %i' % pid).read().split('\n')
if len( pinfo ) > 2:
# You might need to modify this to your own usage...
if pinfo[1].count( sys.argv[0] ):
# Varify that the process found by 'ps' really is still running...
print "Already Running as pid: %i" % pid
sys.exit(1)
# If we get here, we know that the app is not running so we can start a new one...
pf = open(PID_FILE,'wb')
pf.write('%i\n' % os.getpid())
pf.close()
if __name__ == '__main__':
#Do something here!
pass
之后我只保留 pid 文件,因为您实际上不需要担心误报。请注意,您可能需要根据自己的具体用途修改第二步验证!
关于python - 使用 python 确保长时间运行的进程只执行一个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9577802/