美文网首页Python笔记
Python定时任务sched和多线程Timer用法示例对比

Python定时任务sched和多线程Timer用法示例对比

作者: Cedric_h | 来源:发表于2019-07-26 00:23 被阅读0次

    原文:https://blog.csdn.net/uyy203/article/details/89684510

    一、sched的定时任务

    from sched import *
    from time import *
    
    def print_time(msg="default"):
        print("当前时间",time(),msg)
    
    s = scheduler(time,sleep)
    print(time())
    s.enter(5,1,print_time,("延迟5秒,优先级1",))
    s.enter(3,2,print_time,argument=("延迟3秒,优先级2",))
    s.enter(3,1,print_time,argument=("延迟3秒,优先级1",))
    s.run()
    print(time())
    
    
    schedule.enter(delay,priority,action,(arguments,))
    

    第一个参数delay是一个整数或浮点数,代表多少秒后执行这个action任务
    第二个参数priority是优先级,0代表优先级最高,1次之,2次次之,当两个任务是预定在同一个时刻执行时,根据优先级决定谁先执行。
    第三个参数action就是你要执行的任务,可以简单理解成你要执行任务的函数的函数名
    第四个参数arguments是你要传入这个定时执行函数名函数的参数,最好用括号包起来,如果只传入一个参数的时候用括号包起来,该参数后面一定要加一个逗号,如果不打逗号,会出现错误。

    run()一直被阻塞,直到所有任务全部执行结束。每个任务在同一线程中运行,所以如果一个任务执行时间大于其他任务的等待时间,那么其他任务会推迟任务的执行时间,这样保证没有任务丢失,但这些任务的调用时间会比设定的推迟。

    二、多线程Timer执行定时任务

    import time
    from threading import Timer
    
    def print_name(str):
        print("i am "+str)
    
    print("start")
    
    Timer(5,print_name,args=("spiderman",)).start()
    Timer(10,print_name,("superman",)).start()
    
    print("end")
    

    通过多线程,实现定时任务

    在多线程中,如果只通过schedule,会因为线程安全的问题会出现阻塞,一个任务执行,如果没有结束而另一个任务就要等待。

    通过threading.Timer可以避免这个问题效果就是直接执行Print start和print end,而定时任务会分开执行。打印end不会阻塞。

    相关文章

      网友评论

        本文标题:Python定时任务sched和多线程Timer用法示例对比

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