python schedule模块_一个简单的Python调度器

2022-09-10 14:09:25

关于我

一个有思想的程序猿,终身学习实践者,目前在一个创业团队任team lead,技术栈涉及Android、Python、Java和Go,这个也是我们团队的主要技术栈。

Github:https://github.com/hylinux1024

微信公众号:终身开发者(angrycode)

82fe2346-0c27-413b-8e69-256f1211fcee

最近在做项目的时候经常会用到定时任务,由于我的项目是使用Java来开发,用的是SpringBoot框架,因此要实现这个定时任务其实并不难。

后来我在想如果我要在Python中实现,我要怎么做呢?

一开始我首先想到的是Timer

0x00 Timer

这个是一个扩展自threading模块来实现的定时任务。它其实是一个线程。

# 首先定义一个需要定时执行的方法>>> def hello(): print("hello!")# 导入threading,并创建Timer,设置1秒后执行hello方法>>> import threading>>> timer = threading.Timer(1,hello)>>> timer.start()# 1秒后打印>>> hello!

这个内置的工具使用起来也简单,对于熟悉Java的同学来说也是非常容易的。然而我一直能否有一个更加Pythonic的工具或者类库呢?

这时我看到一篇文章介绍Scheduler类库的使用,突然觉得这就是我想要的

0x01 Scheduler

要使用这个库先使用以下命令进行安装

pip install schedule

schedule模块中的方法可读性非常好,而且支持链式调用

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)

如果要执行的方法需要参数呢?

# 需要执行的方法需要传参def job(val): print(f'hello {val}')# schedule.every(2).seconds.do(job)# 使用带参数的do方法schedule.every(2).seconds.do(job, "hylinux")# 执行结果hello hylinuxhello hylinuxhello hylinuxhello hylinuxhello hylinuxhello hylinux...

是不是很简单?

0x02 学习资料

  1. https://bhupeshv.me/A-Simple-Scheduler-in-Python/
  • 作者:weixin_39929138
  • 原文链接:https://blog.csdn.net/weixin_39929138/article/details/110559309
    更新时间:2022-09-10 14:09:25