跳转至

2. schedule定时任务介绍

1. 官方文档

# https://pypi.org/project/schedule/

2. 介绍

## Project description

Python job scheduling for humans. Run Python functions (or any other callable) 
periodically using a friendly syntax.

- A simple to use API for scheduling jobs, made for humans.
- In-process scheduler for periodic jobs. No extra processes needed!
- Very lightweight and no external dependencies.
- Excellent test coverage.
- Tested on Python and 3.6, 3.7, 3.8, 3.9

3. 使用方法

#1. 安装schedule
$ pip install schedule

#2. 用法
import schedule
import time

def job():
    print("I'm working...")

# 每10秒执行一次
schedule.every(10).seconds.do(job)
# 每10分钟执行一次
schedule.every(10).minutes.do(job)
# 每小时执行一次
schedule.every().hour.do(job)
# 每天10:30执行。(我常用)
schedule.every().day.at("10:30").do(job)
# 这个不太了解?
schedule.every(5).to(10).minutes.do(job)
# 每周一执行
schedule.every().monday.do(job)
# 每周三13:15执行
schedule.every().wednesday.at("13:15").do(job)
# 每分钟的第17秒执行
schedule.every().minute.at(":17").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

4. 分析

#1. 引入第三方库schedule
#2. 将我们要执行的代码放入job中,
#3. 然后选择执行的时间,比如每天上午9点执行!
schedule.every().day.at("09:00").do(job)

最后更新: 2022-03-23 05:21:05