python定时任务使用方法如下:
import sched shelder = sched.scheduler(time.time, time.sleep) shelder.enter(2, 0, print_time, ()) shelder.run()
执行顺序说明如下:
1、创建一个定时任务执行的实例
2、将定时任务插入到执行队列中
3、启动定时任务
enter方法的参数说明:
第一个参数是在任务启动多少秒后执行
第二个参数是任务优先级
第三个参数是要执行的方法
第四个参数是方法要传进去的参数,没有的话直接使用()
实例1:顺序执行
import time import sched def print_time(): print 'now the time is:',time.time() def do_some_times(): print 'begin time:',time.time() shelder.enter(2, 0, print_time, ()) shelder.enter(2, 0, print_time, ()) shelder.enter(5, 1, print_time, ()) shelder.run() print 'end time:',time.time() do_some_times()
运行结果:
begin time: 1525682354.85
now the time is: 1525682356.86
now the time is: 1525682356.86
now the time is: 1525682359.86
end time: 1525682359.86
这里后面的时间都是一样的是因为表示的是加入到队列时间
在涉及到多线程的问题时使用上面的方法就会引入线程安全的限制,官方手册上也做了充分的说明,具体如下:
In multi-threaded environments, the scheduler class has limitations with respect to thread-safety, inability to insert a new task before the one currently pending in a running scheduler, and holding up the main thread until the event queue is empty. Instead, the preferred approach is to use the threading.Timer class instead.
最终的意思就是使用threading的Timer进行替代
实例2:线程安全的
from threading import Timer import time def print_time(): print 'now the time is:',time.time() def print_times(): print 'begin time is:',time.time() Timer(5, print_time,(())).start() Timer(10, print_time,(())).start() time.sleep(2) print 'end time is:',time.time() print_times()
运行结果:
begin time is: 1525682440.55
end time is: 1525682442.55
now the time is: 1525682445.55
now the time is: 1525682450.55
实例3:任务自调度
from threading import Timer import time counttimes=3 def print_time(): global counttimes if counttimes > 0: print 'now the time is %d,%f:' % (counttimes,time.time()) Timer(5, print_time,(())).start() counttimes -= 1 def print_times(): print 'begin time is:',time.time() Timer(5, print_time,(())).start() time.sleep(2) print 'end time is:',time.time() print_times()
运行结果:
begin time is: 1525682594.3
end time is: 1525682596.3
now the time is 3,1525682599.300889:
now the time is 2,1525682604.302403:
now the time is 1,1525682609.302912:
附录
常用schelder方法:
scheduler.enterabs(time, priority, action, argument)
scheduler.enter(delay, priority, action, argument)
scheduler.cancel(event)
删除一个任务事件
scheduler.empty()
任务队列是否为空
scheduler.run()
启动任务,执行下一个任务时会进行等待
scheduler.queue
任务队列
参考文档: