python timer模块_python 定时服务模块

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

任务队列

参考文档:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值