• python定时任务-sched模块


    通过sched模块可以实现通过自定义时间,自定义函数,自定义优先级来执行函数。
    范例一
     1 import time
     2 import sched
     3 
     4 schedule = sched.scheduler( time.time,time.sleep)
     5 
     6 def func(string1):
     7     print "now excuted func is %s"%string1
     8 
     9 print "start"
    10 schedule.enter(2,0,func,(1,))
    11 schedule.enter(2,0,func,(2,))
    12 schedule.enter(3,0,func,(3,))
    13 schedule.enter(4,0,func,(4,))
    14 schedule.run()
    15 
    16 print "end"
    schedule是一个对象,叫什么名字都可以
    schedule.enter(delay,priority,action,arguments)
    第一个参数是一个整数或浮点数,代表多少秒后执行这个action任务
    第二个参数priority是优先级,0代表优先级最高,1次之,2次次之,当
    两个任务是预定在同一个时刻执行时,根据优先级决定谁先执行。
    第三个参数就是你要执行的任务,可以简单理解成你要执行任务的函数的函数名
    第四个参数是你要传入这个定时执行函数名函数的参数,最好用括号包起来,如果只传入一个
    参数的时候用括号包起来,该参数后面一定要加一个逗号,如果不打逗号,会出现错误。
    例如schedule.enter(delay, priority, action, (argument1,))
     
    run()一直被阻塞,直到所有任务全部执行结束。每个任务在同一线程中运行,所以如果一个任务执行时间大于
    其他任务的等待时间,那么其他任务会推迟任务的执行时间,这样保证没有任务丢失,但这些任务的调用时间会比设定的推迟。
     
    多线程执行定时任务
    范例二
    1 import time
    2 import sched
    3 from threading import Timer
    4 def print_name(str):
    5     print "i'm %s"%str
    6 print "start"
    7 Timer(5,print_name,("superman",)).start()
    8 Timer(10,print_name,("spiderman",)).start()
    9 print "end"
    通过多线程,实现定时任务
    在多线程中,如果只通过schedule,会因为线程安全的问题会出现阻塞,一个任务执行,如果没有结束而另一个任务就要等待。
    通过threading.Timer可以避免这个问题效果就是直接执行Print start和print end,而定时任务会分开执行。打印end不会阻塞。
     
     
  • 相关阅读:
    Neko's loop HDU-6444(网络赛1007)
    Parameters
    SETLOCAL
    RD / RMDIR Command
    devenv 命令用法
    Cannot determine the location of the VS Common Tools folder.
    'DEVENV' is not recognized as an internal or external command,
    How to change Visual Studio default environment setting
    error signing assembly unknown error
    What is the Xcopy Command?:
  • 原文地址:https://www.cnblogs.com/ArmoredTitan/p/9138509.html
Copyright © 2020-2023  润新知