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

如何停止Python中按Ctrl+C后仍运行的schedule循环?

解决Python定时脚本Ctrl+C无法彻底停止的问题

你的问题根源在于未处理Ctrl+C触发的中断信号,且schedule库的任务队列未被清空,导致已调度的任务仍会继续执行。可以通过以下方式修改代码彻底解决:

方案一:捕获中断异常并清理任务(基础场景)

import schedule
import time

def foo():
    print("定时任务执行")

schedule.every().minute.at(":10").do(foo)

try:
    while True:
        schedule.run_pending()
        time.sleep(1)  # 每秒检查一次,降低CPU占用
except KeyboardInterrupt:
    schedule.clear()  # 清空所有已调度的定时任务
    print("脚本已终止,所有定时任务已清除")

方案二:注册信号处理函数(更健壮的场景)

import schedule
import time
import signal
import sys

def foo():
    print("定时任务执行")

def exit_handler(signum, frame):
    # 清空所有定时任务并退出脚本
    schedule.clear()
    print("已停止所有定时任务,退出脚本")
    sys.exit(0)

# 注册信号处理函数,捕获Ctrl+C对应的SIGINT信号
signal.signal(signal.SIGINT, exit_handler)

schedule.every().minute.at(":10").do(foo)

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

关键说明

  • schedule.clear()会清空所有已添加的定时任务,避免中断后残留任务继续执行
  • 添加time.sleep(1)能大幅降低脚本的CPU使用率,同时完全不影响定时任务的执行精度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:03:37