直接 import sched 就能用,省去 pip 的麻烦。
支持“延迟多少秒后执行” 或者 “在某个时间点执行”。
如果两个任务时间一样,可以给它们设置优先级,谁先跑谁后跑。
需要指出的是,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"))
Python sched 事件调度 延迟执行 定时任务 线程调度
Python内置模块sched支持定时任务调度,无需安装即可使用。可设置延迟执行或指定时间执行,支持任务优先级,结合threading可实现后台非阻塞运行。