python中schedule模块的使用

本文介绍Python中schedule模块的使用方法,包括安装、基本配置及定时任务的实现方式。此外,还探讨了如何解决任务间的时间冲突问题,并提供多线程执行任务的方案。
部署运行你感兴趣的模型镜像

python中schedule模块的使用

标签(空格分隔): python job管理 schedule


python中schedule模块的使用

由于需要用到一个使用python进行job管理的模块,找到了schedule模块,简单好用,在这里记录一下。
详细源码可以参考这里

安装方法

pip install schedule

使用方法
import schedule
import time

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

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)

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

运行该程序之后,可以定时的进行执行。除了代码中提到的方法之外,还有例如seconds等的一些方法,可以参考源码。

TIPS

注意,schedule方法是串行的,也就是说,如果各个任务之间时间不冲突,那是没问题的;如果时间有冲突的话,会串行的执行命令,例如以下代码

import schedule
import time
import threading

def job():
    print("I'm working... in job1  start")
    time.sleep(15)
    print("I'm working... in job1  end")

def job2():
    print("I'm working... in job2")

schedule.every(10).seconds.do(job)
schedule.every(10).seconds.do(job2)

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

输出如下:

I’m working… in job1 start
I’m working… in job1 end
I’m working… in job2

可以改成多线程的方式:

import schedule
import time
import threading

def job():
    print("I'm working... in job1  start")
    time.sleep(15)
    print("I'm working... in job1  end")

def job2():
    print("I'm working... in job2")

def run_threaded(job_func):
     job_thread = threading.Thread(target=job_func)
     job_thread.start()

 schedule.every(10).seconds.do(run_threaded,job)
 schedule.every(10).seconds.do(run_threaded,job2)


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

有如下输出:

I’m working… in job1 start
I’m working… in job2
I’m working… in job1 start
I’m working… in job2
I’m working… in job1 end

可见在并行的执行。
如果想要对线程的数量有所控制,“If you want tighter control on the number of threads use a shared jobqueue and one or more worker threads”,则可以采用如下方法:

import Queue
import time
import threading
import schedule


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


def worker_main():
    while 1:
        job_func = jobqueue.get()
        job_func()

jobqueue = Queue.Queue()

schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)
schedule.every(10).seconds.do(jobqueue.put, job)

worker_thread = threading.Thread(target=worker_main)
worker_thread.start()

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

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

Python的`schedule`模块是一个轻量级的任务调度库,允许开发者以简单的方式安排任务在特定时间或间隔执行。该模块易于使用且功能强大,适用于定时任务的场景,例如定时数据同步、日志清理、定时提醒等。 ### 安装 `schedule`模块不是Python标准库的一部分,因此需要通过`pip`进行安装: ```bash pip install schedule ``` ### 基本使用方法 #### 1. 导入模块并定义任务函数 在使用`schedule`之前,需要导入模块并定义一个或多个任务函数。这些函数将在预定时间被调用。 ```python import schedule import time def job(): print("I'm working...") ``` #### 2. 安排任务执行时间 `schedule`支持多种时间安排方式,包括按秒、分钟、小时、天或特定星期几执行任务。 - **每隔固定时间执行一次任务** ```python schedule.every(10).seconds.do(job) # 每隔10秒执行一次任务 schedule.every(5).minutes.do(job) # 每隔5分钟执行一次任务 schedule.every().hour.do(job) # 每隔1小时执行一次任务 ``` - **每天固定时间执行任务** ```python schedule.every().day.at("10:30").do(job) # 每天的10:30执行一次任务 ``` - **每周固定时间执行任务** ```python schedule.every().monday.do(job) # 每周一的当前时间执行一次任务 schedule.every().wednesday.at("13:15").do(job) # 每周三的13:15执行一次任务 ``` #### 3. 启动调度器 使用`while`循环配合`schedule.run_pending()`方法来持续检查并执行待定任务。通常会配合`time.sleep()`以减少CPU占用率。 ```python while True: schedule.run_pending() time.sleep(1) ``` #### 4. 多个任务调度 可以安排多个任务同时执行,但`schedule`是**串行执行**的,即如果多个任务在同一时间触发,它们将按顺序依次执行。 ```python def job2(): print("Another task is running...") schedule.every(10).seconds.do(job) schedule.every(15).seconds.do(job2) ``` #### 5. 带参数的任务函数 如果任务函数需要参数,可以在`.do()`方法中直接传递: ```python def job_with_arg(name): print(f"Hello, {name}!") schedule.every(5).seconds.do(job_with_arg, name="Alice") ``` ### 注意事项 - `schedule`模块是**单线程**的,任务是按顺序执行的。如果任务耗时较长,可能会影响后续任务的执行时间。 - 适用于轻量级定时任务,对于复杂调度需求(如并发、分布式任务),建议使用更专业的调度框架如`APScheduler`或`Celery`。 ### 示例代码 ```python import schedule import time def greet(name): print(f"Hello, {name}! Current time: {time.strftime('%H:%M:%S')}") # 每隔10秒执行一次 schedule.every(10).seconds.do(greet, name="User") # 每天的10:30执行 schedule.every().day.at("10:30").do(greet, name="Morning Reminder") # 每周三的14:00执行 schedule.every().wednesday.at("14:00").do(greet, name="Weekly Alert") while True: schedule.run_pending() time.sleep(1) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值