1. 程式人生 > 實用技巧 >python 寫crontab 監控程序是否存在 不存在重新啟動

python 寫crontab 監控程序是否存在 不存在重新啟動

完整程式碼

# coding:utf-8
import os
import datetime
import time
from crontab import CronTab

def func_crontab():
    my_user_cron = CronTab(user=True)

    if my_user_cron.crons != []:
        for i in my_user_cron.crons:
            if str(i).find("monitoring_process") != -1:
                print("task exists!!!")
            else:
                job = my_user_cron.new(command='/usr/bin/python3 /home/ljp/py/monitor/avlsdk_python3/monitoring_process.py')
                job.setall('*/2 * * * *')
                job.set_comment("monitoring_process")
                my_user_cron.write()            
    else:
        job = my_user_cron.new(command='/usr/bin/python3 /home/ljp/py/monitor/avlsdk_python3/monitoring_process.py')
        job.setall('*/2 * * * *')
        job.set_comment("monitoring_process")
        my_user_cron.write()
           

def check_process():
    process="aa"

    if os.system("ps -ef|grep %s|grep -v grep" % process) != 256:
        print("process exists")
    else:
        print("process does not exist")
        os.system("python3 aa.py")
if __name__ == '__main__':
    func_crontab()

    check_process()

  crontab 寫入:

# coding:utf-8
import os
import datetime
import time
from crontab import CronTab

def func_crontab():
    my_user_cron = CronTab(user=True)

    if my_user_cron.crons != []:
        for i in my_user_cron.crons:
            if str(i).find("monitoring_process") != -1:
                print("task exists!!!")
            else:
                job = my_user_cron.new(command='/usr/bin/python3 /home/ljp/py/monitor/avlsdk_python3/monitoring_process.py')
                job.setall('*/2 * * * *')
                job.set_comment("monitoring_process")
                my_user_cron.write()            
    else:
        job = my_user_cron.new(command='/usr/bin/python3 /home/ljp/py/monitor/avlsdk_python3/monitoring_process.py')
        job.setall('*/2 * * * *')
        job.set_comment("monitoring_process")
        my_user_cron.write()

        os.system("python3 aa.py")
if __name__ == '__main__':
    func_crontab()

  

 程序監控並重啟

# coding:utf-8
import os
import datetime
import time
from crontab import CronTab


def check_process():
    process="aa"

    if os.system("ps -ef|grep %s|grep -v grep" % process) != 256:
        print("process exists")
    else:
        print("process does not exist")
        os.system("python3 aa.py")

if __name__ == '__main__':
    check_process()