Python 自动定时任务

 写了一个定时执行任务的程序 0点开始启动到第二天的8点,之外的时间段都处于关闭状态。



import os
from datetime import datetime
import psutil

SYSTEM_INIT = "SYSTEM_INIT"

def execute():
    os.system("nohup /bin/" + SYSTEM_INIT + " &")
    print("executed")

def isExecuting():
    pids = psutil.pids()
    ret_val = -999
    for pid in pids:
        PNAME = psutil.Process(pid).name()

        if SYSTEM_INIT == PNAME:
            return pid
    return ret_val

def main():
    dateTime  =  datetime.now()
    HOUR = dateTime.hour;
    weedkey = dateTime.weekday()

    print(weedkey)
    if weedkey == 5 or weedkey == 6:
        pid = isExecuting()
        print(pid)
        if pid == -999:
            execute()
        else:
            return 0;


    # more than 00 less than 08
    if HOUR >= 23 or HOUR < 8:
        # is exisxt
        pid = isExecuting()
        if pid == -999:
            execute();
            return 0


    if HOUR > 8 and HOUR != 23:
        pid = isExecuting();
        if pid != -999:
            psutil.Process(pid).kill()

if __name__ == "__main__":
    main()

只能用于linux端,windows还在进程的处理方面有些问题。

备注:需要安装pstuil包、

由 python 脚本开启的命令,在python退出后,进程资源也会释放。

评论