标签:safe hold argument 引入 env empty time can tps
python定时任务使用方法如下:
import sched shelder = sched.scheduler(time.time, time.sleep) shelder.enter(2, 0, print_time, ()) shelder.run()
执行顺序说明如下:
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
这里后面的时间都是一样的是因为表示的是加入到队列时间
在涉及到多线程的问题时使用上面的方法就会引入线程安全的限制,官方手册上也做了充分的说明,具体如下:
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方法:
标签:safe hold argument 引入 env empty time can tps
原文地址:https://www.cnblogs.com/newzol/p/9003649.html