python 定时任务

转自:https://www.cnblogs.com/LinTeX9527/p/6181523.html

最近学习到了 python 中两种开启定时任务的方法,和你们分享一下心得。html

  • sched.scheduler()
  • threading.Timer()

sched 定时任务

使用sched的套路以下:python

s = sched.scheduler(time.time, time.sleep)
s.enter(delay, priority, func1, (arg1, arg2, ...))
s.enter(delay, priority, func2, (arg1, arg2, arg3, ...))
s.run()

第一步新建一个调度器;markdown

第二步添加任务,能够添加多个任务;多线程

第三步让调度器开始运行。函数

第二步各参数含义:oop

  • delay 相对于调度器添加这个任务时刻的延时,以秒为单位;
  • priority 优先级,数字越小优先级越高;
  • func1 任务函数
  • (arg1, arg2, ...) 任务函数的参数
import time
import sched

# 第一个工做函数
# 第二个参数 @starttime 表示任务开始的时间
# 很明显参数在创建这个任务的时候就已经传递过去了,至于任务什么时候开始执行就由调度器决定了
def worker(msg, starttime):
    print u"任务执行的时刻", time.time(), "传达的消息是", msg, '任务创建时刻', starttime


# 建立一个调度器示例
# 第一参数是获取时间的函数,第二个参数是延时函数
print('----------  两个简单的例子  -------------')
print('程序启动时刻:', time.time())
s = sched.scheduler(time.time, time.sleep)
s.enter(1, 1, worker, ('hello', time.time()))
s.enter(3, 1, worker, ('world', time.time()))
s.run()  # 这一个 s.run() 启动上面的两个任务
print('睡眠2秒前时刻:', time.time())
time.sleep(2)
print('睡眠2秒结束时刻:', time.time())


# 重点关注下面2个任务,创建时间,启动时间
# 2个任务的创建时间都很好计算,但有没有发现 "hello world [3]" 的启动时间比创建时间晚 13 秒,
# 这不就是2个 sleep 的总延时吗?因此说启动时间并不必定就是 delay 能指定的,还须要看具体的程序环境,
# 若是程序堵塞的很厉害,已经浪费了一大段的时间尚未到 scheduler 能调度这个任务,当 scheduler 能调度这个
# 任务的时候,发现 delay 已通过去了, scheduler 为了弥补“罪过”,会立刻启动这个任务。

# 任务 "hello world [15]" 就是一个很好的例子,正常状况下,程序没有阻塞的那么厉害,在scheduler 能调度这个任务的时候
# 发现 delay 还没到就等待,若是 delay 时间到了就能够在刚好指定的延时调用这个任务。
print('\n\n----------  两个复杂的例子  -------------')
s.enter(3, 1, worker, ('hello world [3]', time.time()))
print('睡眠7秒前时刻:', time.time())
time.sleep(7)
print('睡眠7秒结束时刻:', time.time())


s.enter(15, 1, worker, ('hello world [15]', time.time()))
print('睡眠6秒前时刻:', time.time())
time.sleep(6)
print('睡眠6秒结束时刻:', time.time())

s.run() # 过了2秒以后,启动另一个任务


print('程序结束时刻', time.time())
----------  两个简单的例子  -------------
程序启动时刻: 1481731389.4
任务执行的时刻 1481731390.4 传达的消息是 hello 任务创建时刻 1481731389.4
任务执行的时刻 1481731392.41 传达的消息是 world 任务创建时刻 1481731389.4
睡眠2秒前时刻: 1481731392.41
睡眠2秒结束时刻: 1481731394.41


----------  两个复杂的例子  -------------
睡眠7秒前时刻: 1481731394.41
睡眠7秒结束时刻: 1481731401.42
睡眠6秒前时刻: 1481731401.42
睡眠6秒结束时刻: 1481731407.42
任务执行的时刻 1481731407.42 传达的消息是 hello world [3] 任务创建时刻 1481731394.41
任务执行的时刻 1481731416.43 传达的消息是 hello world [15] 任务创建时刻 1481731401.42
程序结束时刻 1481731416.43

自调任务1

任务快结束时利用 scheduler 又从新调用本身让本身“活过来”。post

# 计数器,一个循环任务,总共让本身执行3次
total = 0 
# 第二个工做函数,自调任务,本身开启定时并启动。
def worker2(msg, starttime):
    global total
    total += 1
    print('当前时刻:', time.time(), '消息是:', msg, ' 启动时间是:', starttime)
    # 只要没有让本身调用到第3次,那么继续重头开始执行本任务
    if total < 3:
        # 这里的delay 能够从新指定
        s.enter(5, 2, worker2, ('perfect world %d' % (total), time.time()))
        s.run()

print('程序开始时刻:', time.time())
# 开启自调任务
s.enter(5, 2, worker2, ('perfect world %d' % (total), time.time()))
s.run()
print('程序结束时刻:', time.time())
程序开始时刻: 1481731439.42
当前时刻: 1481731444.43 消息是: perfect world 0  启动时间是: 1481731439.42
当前时刻: 1481731449.44 消息是: perfect world 1  启动时间是: 1481731444.43
当前时刻: 1481731454.44 消息是: perfect world 2  启动时间是: 1481731449.44
程序结束时刻: 1481731454.44

Threading.Timer() 定时任务

from threading import Timer import time def func(msg, starttime): print('程序启动时刻:', starttime, '当前时刻:', time.time(), '消息内容 --> %s' % (msg)) # 下面的两个语句和上面的 scheduler 效果同样的 Timer(5, func, ('hello', time.time())).start() Timer(3, func, ('world', time.time())).start()
程序启动时刻: 1481731467.28 当前时刻: 1481731470.28 消息内容 --> world
程序启动时刻: 1481731467.28 当前时刻: 1481731472.28 消息内容 --> hello

循环任务2

利用 threading.Timer() 创建的自调任务学习

count = 0
def loopfunc(msg,starttime):
    global count
    print('启动时刻:', starttime, ' 当前时刻:', time.time(), '消息 --> %s' % (msg))
    count += 1
    if count < 3:
        Timer(3, loopfunc, ('world %d' % (count), time.time())).start()

Timer(3, loopfunc, ('world %d' % (count), time.time())).start()
启动时刻: 1481731476.35  当前时刻: 1481731479.35 消息 --> world 0
启动时刻: 1481731479.35  当前时刻: 1481731482.35 消息 --> world 1
启动时刻: 1481731482.35  当前时刻: 1481731485.35 消息 --> world 2
 
自用,测试,待完善......
方法一(推荐使用)
from threading import Timer
import time

def interval_time(timeStr):
    #timeStr = '2018-5-3 09:48:15'  时间格式
    #调用格式 interval_time('2018-5-3 09:48:05')
    timeArray = time.strptime(timeStr, "%Y-%m-%d %H:%M:%S")
    timestamp = time.mktime(timeArray)
    return int(timestamp-time.time())

def func(msg, starttime):
    print('程序启动时刻:', starttime, '当前时刻:', time.time(), '消息内容 --> %s' % (msg))
    
# 下面的两个语句和上面的 scheduler 效果同样的
Timer(interval_time('2018-5-3 09:48:05'), func, ('hello', time.time())).start()
Timer(interval_time('2018-5-3 09:48:15'), func, ('world', time.time())).start()

方法二(使用sched)测试

#coding=utf-8
#这里须要引入二个模块,若是须要使用系统cmd,增长os模块执行cmd命令
import time, sched
import threading  
    
# 第一个参数肯定任务的时间,返回从某个特定的时间到如今经历的秒数  
# 第二个参数以某种人为的方式衡量时间  
schedule = sched.scheduler(time.time, time.sleep)  

# 计算距离当前时间的秒数
def calc_time(timeStr): #timeStr = '2017-3-7 23:59:00' 时间格式 timeArray = time.strptime(timeStr, "%Y-%m-%d %H:%M:%S") timestamp = time.mktime(timeArray) return int(timestamp-time.time()) #待运行主函数 def perform_command(id, timeStr): print('定时任务 {0} ,计划时间:{1}, 当前时间:'.format(id, timeStr),time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # print(arg) #示例函数 def timming_exe(arg, inc = 60): # enter用来安排某事件的发生时间,从如今起第n秒开始启动
#enter 延迟时间 优先级 回调函数 参数
schedule.enter(inc, 0, perform_command, (arg,)) # 持续运行,直到计划时间队列变成空为止 schedule.run() #--------如下自编测试,方便调用-----------仅需增长或修改args #多线程运行主函数 def run_threading(id, timeStr): mythread = threading.Thread(target=perform_command, args=(id, timeStr)) mythread.start() #写入计划定时任务的函数 def execute_at_time(id, timeStr, func): inc = calc_time(timeStr) schedule.enter(inc, 0, func, (id, timeStr))
    #schedule.enter(inc1, 0, func, (id, timeStr))
    #schedule.enter(inc2, 0, func, (id, timeStr))
    #schedule.enter(inc3, 0, func, (id, timeStr)) schedule.run()
def main(): execute_at_time('1', '2018-5-2 22:43:20', run_threading) execute_at_time('2', '2018-5-2 22:43:30', run_threading) execute_at_time('4', '2018-5-2 22:43:40', run_threading) execute_at_time('5', '2018-5-2 22:43:50', run_threading) execute_at_time('6', '2018-5-2 22:43:55', run_threading) execute_at_time('7', '2018-5-2 22:44:20', run_threading) execute_at_time('8', '2018-5-2 22:44:30', run_threading) execute_at_time('9', '2018-5-2 22:44:50', run_threading) execute_at_time('10', '2018-5-2 22:44:55', run_threading) if __name__ == '__main__': main()
相关文章
相关标签/搜索