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 importTimerimporttimedefprint_time():print 'now the time is:',time.time()defprint_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 importTimerimporttime
counttimes=3
defprint_time():globalcounttimesif counttimes >0:print 'now the time is %d,%f:' %(counttimes,time.time())
Timer(5, print_time,(())).start()
counttimes-= 1
defprint_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
任务队列
参考文档: