在我们的实际开发中,经常有这样的一种需求:要求某个功能模块或任务在相同的时间周期内进行循环执行。这里有了一个定时器的概念,具体而言我们应该如何去实现一个定时器呢?定时器有许多很实用的功能,能够控制线程的执行、减少系统的消耗等。现在我们来动手实践实现Python3中的定时功能吧。
比如使用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实现任务的定时循环执行的详细内容。更多信息请关注PHP中文网其他相关文章!

我们今天主要是来看一看golang time 包的时间应用方式。两者的一般规则是「wall time」用于告知时间,而「monotonic clock」用于测量时间;除外还有其他的时钟处理方式。

1.概述作为本文的一部分,让我们从现有Date和CalendarAPI存在的一些问题入手,来探讨新的Java8Date和TimeAPI如何解决这些问题。我们还将搞一搞Java8时间类库中的核心类,比如LocalDate,LocalTime,LocalDateTime,ZonedDateTime,Period,Duration以及它们的api。2.旧的时间API(java8之前)的问题线程安全-Date和Calendar类不是线程安全的,使开发者难以调试这些api的并发问题,需要编写额外的代码来处

Pythontime模块时间获取和转换Python的Time库可以进行时间相关的处理,如访问当前日期和时间,输出不同格式的时间以及等待指定的时间等。1.获取时间1.1.时间戳importtimetimestamp=time.time()#1682737552.5009851格林威治时间(GMT)1970年01月01日00时00分00秒起至现在的总秒数1.2.结构化时间importtimestruct_time=time.localtime()#time.struct_time(tm_year=2

一.Python中表示时间的两种方式:时间戳:相对于1970.1.100:00:00以秒计算的偏移量,唯一的时间元组struct_time:共有9个元素>tm_year:年1-12>tm_mon:月1-12>tm_mday:日1-31>tm_hour:时0-23>tm_min:分0-59>tm_sec:秒0-59>tm_wday:星期0-6(0表示周日)>tm_day:一年中的第几天1-366>tm_isdst:是否是夏令,默认为-1二.ti

Python3.x中如何使用threading模块创建和管理线程简介:随着计算机的强大性能,多线程成为一种常见的并行处理方式。而在Python的标准库中,就有一个方便的模块-threading。本文将介绍如何使用Python3.x中的threading模块创建和管理线程,并使用代码示例进行说明。一、什么是线程?线程是一个在单个进程中执行的独立流程。

Java是一门强大的编程语言,具有丰富的API库,可以帮助我们快速开发应用程序。在JavaAPI开发中,使用Threading进行线程管理是不可避免的,因为线程管理是Java应用程序中的一个核心问题。本文将介绍如何使用Threading进行线程管理。一、什么是JavaAPI中的Threading?首先,了解Threading是一个什么东西。Java中的

安装步骤:1、确保已经安装了Python3,并且可以通过命令行访问;2、打开终端,输入“python3 -m ensurepip --upgrade”命令来安装pip;3、从Python官方网站下载pip的安装包;4、将下载的pip安装包解压到一个目录中;5、打开终端,并导航到解压后的pip目录;6、运行“python3 setup.py install”命令安装pip即可。

Golang是一门非常受欢迎的编程语言,其简单易学、高效快速的特性吸引了越来越多的开发者。但在使用中,不可避免地会遇到一些问题和错误。例如,使用time包中的After方法时,可能会遇到undefined:time.After的错误。本篇文章将为大家介绍如何解决这个错误。了解错误原因在Golang中,如果我们使用了一个未导出的函数名或未正


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6
视觉化网页开发工具

WebStorm Mac版
好用的JavaScript开发工具