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

比如使用Python在进行爬虫系统开发时可能就需要间隔一段时间就重复执行的任务的需求,从而实现一个线程服务在后台监控数据的抓取状态,这里定时器就可以帮忙了。
【视频推荐:Python3视频教程】
【手册推荐:Python中文手册】
通过Python的文档我们可以找到threading.Timer()来实现定时功能:
简单实现代码:
1 2 3 4 5 6 7 8 9 10 11 | 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.定时任务代码
1 2 3 4 5 6 7 8 9 10 11 12 | #!/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.周期性执行任务
1 2 3 4 5 6 7 8 9 10 11 12 | #!/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.循环执行命令
1 2 3 4 5 6 7 | #!/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
阅读剩余部分
相关阅读 >>
Python中的函数介绍
Python求绝对值的方法有哪些
Python怎么把三位数拆开
Python shell怎么运行
从零学Python用什么书
Python3文件操作相关的实力分享
Python 的二元算术运算详解
Python怎么统计txt文件的字数
导入Python标准数学函数模块的语句是什么
Python中日期和时间格式化输出的方法小结_Python
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 通过Python3实现任务的定时循环执行