比方运用Python在举行爬虫体系开辟时能够就需要距离一段时候就反复实行的使命的需求,从而完成一个线程效劳在背景监控数据的抓取状况,这里定时器就能够帮助了。
【视频引荐:Python3视频教程】
【手册引荐:Python中文手册】
经由过程Python的文档我们能够找到threading.Timer()来完成定时功用:
简朴完成代码:
import threading def func1(a): #Do something print('Do something') a+=1 print(a) print('当前线程数为{}'.format(threading.activeCount())) if a>5: return t=threading.Timer(5,func1,(a,)) t.start()
效果图:
经由过程查阅材料,应用Python能完成三种差别的定时使命实行体式格局:
1.定时使命代码
#!/user/bin/env python #定时实行使命敕令 import time,os,sched schedule = sched.scheduler(time.time,time.sleep) def perform_command(cmd,inc): os.system(cmd) print('task') def timming_exe(cmd,inc=60): schedule.enter(inc,0,perform_command,(cmd,inc)) schedule.run() print('show time after 2 seconds:') timming_exe('echo %time%',2)
2.周期性实行使命
#!/user/bin/env python import time,os,sched schedule = sched.scheduler(time.time,time.sleep) def perform_command(cmd,inc): #在inc秒后再次运转本身,即周期运转 schedule.enter(inc, 0, perform_command, (cmd, inc)) os.system(cmd) def timming_exe(cmd,inc=60): schedule.enter(inc,0,perform_command,(cmd,inc)) schedule.run()#延续运转,直到设计时候行列变成空为止 print('show time after 2 seconds:') timming_exe('echo %time%',2)
3.轮回实行敕令
#!/user/bin/env python import time,os def re_exe(cmd,inc = 60): while True: os.system(cmd) time.sleep(inc) re_exe("echo %time%",5)
总结而言:Python完成定时器的要领都是schedule和threading的完成,细致的用法还要依据现实情况灵活运用。
最经常使用的两个模块:threading、Sched
threading模块运用:
import threading ,time from time import sleep, ctime class Timer(threading.Thread): """ very simple but useless timer. """ def __init__(self, seconds): self.runTime = seconds threading.Thread.__init__(self) def run(self): time.sleep(self.runTime) print ("Buzzzz!! Time's up!") class CountDownTimer(Timer): """ a timer that can counts down the seconds. """ def run(self): counter = self.runTime for sec in range(self.runTime): print (counter) time.sleep(1.0) counter -= 1 print ("Done") class CountDownExec(CountDownTimer): """ a timer that execute an action at the end of the timer run. """ def __init__(self, seconds, action, args=[]): self.args = args self.action = action CountDownTimer.__init__(self, seconds) def run(self): CountDownTimer.run(self) self.action(self.args) def myAction(args=[]): print ("Performing my action with args:") print (args) if __name__ == "__main__": t = CountDownExec(3, myAction, ["hello", "world"]) t.start() print("2333")
Sched模块运用:
''' 运用sched模块完成的timer,sched模块不是轮回的,一次调理被实行后就Over了,假如想再实行, 能够运用while轮回的体式格局不断的挪用该要领 ''' import time, sched #被调理触发的函数 def event_func(msg): print("Current Time:", time.strftime("%y-%m-%d %H:%M:%S"), 'msg:', msg) def run_function(): #初始化sched模块的scheduler类 s = sched.scheduler(time.time, time.sleep) #设置一个调理,由于time.sleep()的时候是一秒,所以timer的距离时候就是sleep的时候,加上enter的第一个参数 s.enter(0, 2, event_func, ("Timer event.",)) s.run() def timer1(): while True: #sched模块不是轮回的,一次调理被实行后就Over了,假如想再实行,能够运用while轮回的体式格局不断的挪用该要领 time.sleep(1) run_function() if __name__ == "__main__": timer1()
以上就是经由过程Python3完成使命的定时轮回实行的细致内容,更多请关注ki4网别的相干文章!