为什么我有两个由cron运行的相同脚本的副本?

时间:2018-03-30 09:10:34

标签: python process cron ps

我只有一行致力于我每15分钟运行一次的脚本:

*/30 0-3,5-9,11-15,17-21,23 * * * ~/env/bin/python2 ~/hasoffers_api/script.py > ~/hasoffers_api/logs/script_`date +\%Y\%m\%d\%H\%M\%S`.log 2>&1

如果第一个实例还没有停止工作(脚本是用Python编写的),那么脚本本身在内部保护不运行两次:

def checkPidRunning(pid):
    global script_name
    if pid<1:
        print "Incorrect pid number!"
        exit()
        try:
            os.kill(pid, 0)
        except OSError:
            print "Abnormal termination of previous process."
            return False
    else:
        ps_command = "ps -p %s -o cmd h | grep %s" % (pid, script_name)
        # ipdb.set_trace()
        process_exist = os.system(ps_command)
        if process_exist == 0:
            return True
        else:
            print "Process with pid %s is not a Python process. Continue..." % pid
            return False

if __name__ == '__main__':
    script_name = os.path.basename(__file__)
    pid = str(os.getpid())
    pidfile = os.path.join("/", "tmp/", script_name + ".pid")
    if os.path.isfile(pidfile):
        print "Warning! Pid file %s existing. Checking for process..." % pidfile
        r_pid = int(file(pidfile, 'r').readlines()[0])
        if checkPidRunning(r_pid):
            print "Python process with pid = %s is already running. Exit!" % r_pid
            exit()
        else:
            file(pidfile, 'w').write(pid)
    else:
        file(pidfile, 'w').write(pid)
    try:
        doing_stuff()
    finally:
        os.unlink(pidfile)

问题是:

当我通过ps aux |检查脚本时,为什么会看到脚本被运行两次grep python:

pavel     1502  0.0  0.0   4388   824 ?        Ss   09:00   0:00 /bin/sh -c ~/env/bin/python2 ~/hasoffers_api/scruot.py > ~/hasoffers_api/logs/script_`date +%Y%m%d%H%M%S`.log 2>&1
pavel     1541 26.9  1.9 2633524 159692 ?      Sl   09:00  16:55 /home/pavel/env/bin/python2 /home/pavel/hasoffers_api/script.py

唯一的细节 - 我在脚本中使用ThreadPoolExecutor模式,但是它的线程,而不是进程...

0 个答案:

没有答案