关于我
编程界的一名小小程序猿,目前在一个创业团队任team lead,技术栈涉及Android、Python、Java和Go,这个也是咱们团队的主要技术栈。 联系:hylinux1024@gmail.compython
最近在作项目的时候常常会用到定时任务,因为个人项目是使用Java
来开发,用的是SpringBoot
框架,所以要实现这个定时任务其实并不难。linux
后来我在想若是我要在Python
中实现,我要怎么作呢? 一开始我首先想到的是Timer
编程
这个是一个扩展自threading
模块来实现的定时任务。它实际上是一个线程。小程序
# 首先定义一个须要定时执行的方法
>>> def hello():
print("hello!")
# 导入threading,并建立Timer,设置1秒后执行hello方法
>>> import threading
>>> timer = threading.Timer(1,hello)
>>> timer.start()
# 1秒后打印
>>> hello!
复制代码
这个内置的工具使用起来也简单,对于熟悉Java
的同窗来讲也是很是容易的。然而我一直可否有一个更加Pythonic
的工具或者类库呢?框架
这时我看到一篇文章介绍Scheduler
类库的使用,忽然以为这就是我想要的工具
要使用这个库先使用如下命令进行安装学习
pip install schedule
复制代码
schedule
模块中的方法可读性很是好,并且支持链式调用spa
import schedule
# 定义须要执行的方法
def job():
print("a simple scheduler in python.")
# 设置调度的参数,这里是每2秒执行一次
schedule.every(2).seconds.do(job)
if __name__ == '__main__':
while True:
schedule.run_pending()
# 执行结果
a simple scheduler in python.
a simple scheduler in python.
a simple scheduler in python.
...
复制代码
其它设置调度参数的方法线程
# 每小时执行
schedule.every().hour.do(job)
# 天天12:25执行
schedule.every().day.at("12:25").do(job)
# 每2到5分钟时执行
schedule.every(5).to(10).minutes.do(job)
# 每星期4的19:15执行
schedule.every().thursday.at("19:15").do(job)
# 每第17分钟时就执行
schedule.every().minute.at(":17").do(job)
复制代码
若是要执行的方法须要参数呢?code
# 须要执行的方法须要传参
def job(val):
print(f'hello {val}')
# schedule.every(2).seconds.do(job)
# 使用带参数的do方法
schedule.every(2).seconds.do(job, "hylinux")
# 执行结果
hello hylinux
hello hylinux
hello hylinux
hello hylinux
hello hylinux
hello hylinux
...
复制代码
是否是很简单?