You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python schedule模块中于任务运行后仅打印一次下次运行时间?

使用Python schedule模块实现任务完成后仅打印一次下次运行时间

问题场景

当前代码每秒都会重复打印next job scheduled at {next_job_time},不符合仅在任务完成后打印一次的需求:

import schedule
import time

def Job():
    #doing something...

schedule.every(1).hours.do(Job)

while True:
    schedule.run_pending()
    print(f"next job scheduled at {schedule.next_run()}")
    time.sleep(1)

尝试用装饰器包裹任务函数时,打印的是当前执行时间而非正确的下次运行时间,核心原因是若装饰器在任务执行过程中获取时间,schedule尚未完成任务状态更新与下次时间计算。

解决方案

方法一:跟踪下次运行时间的变化

维护变量记录上次的下次运行时间,每次循环时对比当前时间,仅当时间发生变化(即任务刚执行完成并更新了时间)时打印:

import schedule
import time

def Job():
    # 任务执行逻辑
    print("任务执行完成")

# 配置任务(示例用10秒方便测试,实际可改回1小时)
schedule.every(10).seconds.do(Job)

# 初始化记录第一次的下次运行时间
last_next_run = schedule.next_run()
print(f"初始下次任务时间: {last_next_run}")

while True:
    schedule.run_pending()
    current_next_run = schedule.next_run()
    # 只有当下次运行时间变化时才打印
    if current_next_run != last_next_run:
        print(f"next job scheduled at {current_next_run}")
        last_next_run = current_next_run
    time.sleep(1)

方法二:任务执行完成后直接打印(修正装饰器用法)

确保装饰器在任务执行完成后再获取并打印下次运行时间,此时schedule已经完成任务状态更新与下次时间计算:

import schedule
import time

def print_next_run_after_task(func):
    def wrapper(*args, **kwargs):
        # 先执行任务逻辑
        func_result = func(*args, **kwargs)
        # 任务完成后,schedule已更新下次运行时间,直接获取打印
        print(f"next job scheduled at {schedule.next_run()}")
        return func_result
    return wrapper

@print_next_run_after_task
def Job():
    print("任务执行中...")

schedule.every(10).seconds.do(Job)

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

说明

两种方法都能实现仅在任务完成后打印一次正确的下次运行时间:

  • 方法一通过时间对比,适合需要统一管理打印逻辑的多任务场景;
  • 方法二将打印逻辑和任务绑定,更直观,适合单个任务的场景。

内容的提问来源于stack exchange,提问作者TheSpaceSheep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:42:39