• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

通过Python3实现任务的定时循环执行

python 搞代码 4年前 (2022-01-09) 66次浏览 已收录 0个评论

在我们的实际开发中,经常有这样的一种需求:要求某个功能模块或任务在相同的时间周期内进行循环执行。这里有了一个定时器的概念,具体而言我们应该如何去实现一个定时器呢?定时器有许多很实用的功能,能够控制线程的执行、减少系统的消耗等。现在我们来动手实践实现Python3中的定时功能吧。

比如使用Python在进行爬虫系统开发时可能就需要间隔一段时间就重复执行的任务的需求,从而实现一个线程服务在后台监控数据的抓取状态,这里定时器就可以帮忙了。

【视频推荐:Python3视频教程】

【手册推荐:Python中文手册】

通过Python的文档我们可以找到threading.Timer()来实现定时功能:

简单实现代码:

import threadingdef 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,schedschedule = 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 pythonimport time,os,schedschedule = 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 pythonimport time,osdef 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 ,timefrom time import sleep, ctimeclass Timer(threading.Thread):        """        very simple b<strong style="color:transparent">本文来源gaodai#ma#com搞@@代~&码网^</strong>ut 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")

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:通过Python3实现任务的定时循环执行

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址