简单的Python调度器Schedule详解

yipeiwu_com6年前Python基础

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

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

一开始我首先想到的是Timer

Timer

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

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

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

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

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 hylinux
hello hylinux
hello hylinux
hello hylinux
hello hylinux
hello hylinux
...

是不是很简单?

学习资料

https://bhupeshv.me/A-Simple-Scheduler-in-Python/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3内置模块之json编解码方法小结【推荐】

Python3中我们利用内置模块 json 解码和编码 JSON对象 ,JSON(JavaScript Object Notation)是指定 RFC 7159(废弃了RFC 4627)...

Python splitlines使用技巧

复制代码 代码如下:mulLine = """Hello!!! Wellcome to Python's world! There are a lot of interesting th...

python3下使用cv2.imwrite存储带有中文路径图片的方法

由于imwrite前使用编码在python3中已经不适用,可用imencode代替,以下代码是从视频中获取第2帧保存在中文文件夹下的实例: cap = cv2.VideoCaptur...

《与孩子一起学编程》python自测题

测试题一、 1、 程序可以响应的两种事件分别是键盘事件和鼠标事件。 2、 处理事件的代码称为事件处理器 3、 Pygame使用KEYDOWN事件来检测按键是否按下。 4、 Pos...

Python正则表达式指南 推荐

Python正则表达式指南 推荐

本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达式标准库的完整介绍及使用示例。本文的内容不包括如何编写高效的正则表达式、如何优化正则表达式,这些主题...