目录

python中定时任务sched库用法详解

目录

python中定时任务sched库用法详解

sched是一种调度(延时处理机制)。

sched是python内置库,不需要安装。

示例代码:

import sched
import time
from datetime import datetime

# 初始化sched模块的scheduler类
# 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)


def task(inc):
    now = datetime.now()
    ts = now.strftime("%Y-%m-%d %H:%M:%S")
    print(ts)
    schedule.enter(inc, 0, task, (inc,))


def func(inc=3):
    # enter四个参数分别为:
    # 间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数、给该触发函数的参数(tuple形式)
    schedule.enter(0, 0, task, (inc,))
    schedule.run()


func()

运行结果:

https://i-blog.csdnimg.cn/blog_migrate/f858e2cf7101fb6a778eff278ae68ef5.png

注意: 根据Python官方文档和相关资料,sched模块没有明确的最大深度限制。但是,随着任务数量的增加,调度器的性能会受到影响,可能会导致调度器过于繁忙,从而影响程序的性能。因此,在使用sched模块实现定时任务时,需要合理设置任务数量和调度频率,考虑使用多线程或异步编程等方式提高程序效率。