
import os
import psutil
from apscheduler.schedulers.blocking import BlockingScheduler



def monitor(_exe,_file,args=[]):
    _flag = False
    if _file is not None and _file!="":
        if os.path.exists(_file):
            _file = os.path.abspath(_file)
        else:
            print("file not exists")
    for _p in psutil.process_iter():
        try:
            proc_info = _p.as_dict(attrs={"pid","name","exe","cmdline"})
            _cmdline = proc_info.get("cmdline",[])
            if len(_cmdline)>=2:
                _exe_file = _cmdline[1]
                if os.path.exists(_exe_file):
                    if os.path.abspath(_exe_file)==_file:
                        _flag = True
                        print("process %s %s is processing"%(_exe,_file))
        except Exception as e:
            print(str(e))
    if not _flag:
        os.system("nohup %s %s %s &"%(_exe,_file," ".join(args)))

def monitor_processes():
    list_process = [{"exe":"/root/ENV/bin/python",
                     "file":"/root/BaseDataMaintenance/start_sychro_attachFix.py"}]
    for _process in list_process:
        monitor(_process.get("exe",""),_process.get("file",""),[])

def start_monitor():
    schedule = BlockingScheduler()
    schedule.add_job(monitor_processes,"cron",minute="*/1")
    schedule.start()

if __name__=="__main__":
    start_monitor()