Schedule of Py: Detailed guide to the introduction, installation and usage of schedule

Schedule of Py: Detailed guide to the introduction, installation and usage of schedule

Table of contents

Introduction to schedule

Installation of schedule

How to use schedule

1. Use the schedule library to arrange and execute different tasks


Introduction to schedule

Human-friendly Python task scheduling. Run a Python function (or any other callable object) periodically using friendly syntax. An easy-to-use API tailored for humans for scheduling tasks. In-memory scheduler for periodic tasks. No additional process required! Very lightweight and no external dependencies. Excellent test coverage. Tested on Python and versions 3.7, 3.8, 3.9, 3.10, 3.11.

GitHub地址GitHub - dbader/schedule: Python job scheduling for humans.

Installation of schedule

pip install -i https://mirrors.aliyun.com/pypi/simple schedule

How to use schedule

1. Use the schedule library to arrange and execute different tasks


import schedule
import time

# 定义任务函数
def job():
    print("I'm working...")

# 设定定时任务
'''
使用schedule库设定不同的定时任务,
例如每10秒执行一次、每10分钟执行一次、每小时执行一次、每天10:30执行一次、
每5到10分钟之间执行一次、每周一执行一次、
每周三13:15执行一次、每天12:42(使用"Europe/Amsterdam"时区)执行一次、
每分钟的第17秒执行一次。
'''
schedule.every(10).seconds.do(job)
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().day.at("12:42", "Europe/Amsterdam").do(job)
schedule.every().minute.at(":17").do(job)


# 定义带参数的任务函数
def job_with_argument(name):
    print(f"I am {name}")

# 使用schedule库设定每10秒执行一次的任务,并传递参数"name"为"Peter"。
schedule.every(10).seconds.do(job_with_argument, name="Peter")

# 执行定时任务循环
while True:
    schedule.run_pending()
    time.sleep(1)
# 在无限循环中,调用schedule.run_pending()来运行尚未执行的任务,然后通过time.sleep(1)让程序休眠1秒,以避免过度占用CPU资源。

Guess you like

Origin blog.csdn.net/qq_41185868/article/details/134541822