美文网首页
python 定时执行任务 schedule

python 定时执行任务 schedule

作者: 逍遥_yjz | 来源:发表于2021-05-21 11:29 被阅读0次

    1. 安装schedule

    pip install schedule 
    

    2. 编程

    2.1 入门

    import schedule
    import time
    
    def job(name):
        print("her name is : ", name)
    
    name = "longsongpong"
    schedule.every(10).minutes.do(job, name)
    schedule.every().hour.do(job, name)
    schedule.every().day.at("10:30").do(job, name)
    schedule.every(5).to(10).days.do(job, name)
    schedule.every().monday.do(job, name)
    schedule.every().wednesday.at("13:15").do(job, name)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    
    
    每隔十分钟执行一次任务
    每隔一小时执行一次任务
    每天的10:30执行一次任务
    每隔5到10天执行一次任务 
    每周一的这个时候执行一次任务
    每周三13:15执行一次任务
    run_pending:运行所有可以运行的任务
    

    schedule方法是串行的,也就是说,如果各个任务之间时间不冲突,那是没问题的;如果时间有冲突的话,会串行的执行命令
    代码如下:

    import schedule
    import time
    import threading
    
    def job():
        print("I'm working... in job1  start")
        time.sleep(15)
        print("I'm working... in job1  end")
    
    def job2():
        print("I'm working... in job2")
    
    schedule.every(10).seconds.do(job)
    schedule.every(10).seconds.do(job2)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    
    

    结果如下:
    I’m working… in job1 start
    I’m working… in job1 end
    I’m working… in job2

    2.2 多线程并发运行

    import schedule
    import time
    import threading
    
    def job():
        print("I'm working... in job1  start")
        time.sleep(15)
        print("I'm working... in job1  end")
    
    def job2():
        print("I'm working... in job2")
    
    def run_threaded(job_func):
         job_thread = threading.Thread(target=job_func)
         job_thread.start()
    
     schedule.every(10).seconds.do(run_threaded,job)
     schedule.every(10).seconds.do(run_threaded,job2)
    
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    结果如下:
    I’m working… in job1 start
    I’m working… in job2
    I’m working… in job1 start
    I’m working… in job2
    I’m working… in job1 end
    I’m working… in job1 start
    I’m working… in job2

    3. 定时执行脚本

    def test():
        print("运行核心程序")
    
    def timed_Task():
        test()
    
    if __name__ == '__main__':
       
        schedule.every().day.at("08:40").do(timed_Task)
        while True:
            schedule.run_pending()
            time.sleep(10)
    

    3. 总结

    如果schedule的时间间隔设置得比job执行的时间短,一样会线程堆积形成灾难,也就是说,我job的执行时间是1个小时,但是我定时任务设置的是5分钟一次,那就会一直堆积线程。

    相关文章

      网友评论

          本文标题:python 定时执行任务 schedule

          本文链接:https://www.haomeiwen.com/subject/uwtwjltx.html