python sched 自带的轻量级定时任务

sched 主要包含下面几个特点

1. 纯内置,无需安装

直接 import sched 就能用,省去 pip 的麻烦。

2. 事件调度机制简单

支持“延迟多少秒后执行” 或者 “在某个时间点执行”。

3. 可自定义优先级

如果两个任务时间一样,可以给它们设置优先级,谁先跑谁后跑。

需要指出的是,sched.run() 是阻塞的,有时候我们想让它在后台运行,可以用 threading

import sched
import time
import threading

scheduler = sched.scheduler(time.time, time.sleep)

def job():
    print("执行任务:", time.strftime("%X"))

def run_scheduler():
    scheduler.run()

# 安排任务
scheduler.enter(3, 1, job)

# 开线程跑调度器
t = threading.Thread(target=run_scheduler)
t.start()

print("主线程还能继续干别的事哦:", time.strftime("%X"))

作者:spike

分类: Python

创作时间:2025-10-18

更新时间:2025-10-21

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1