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

如何实现定时任务的倒计时功能?解决终端刷屏问题

实现无刷屏的倒计时功能

原始代码

import schedule
import time
from datetime import datetime

scheduleTime = input('Scheduled time: (00:00:00 format)  ')

def time_scheduler():
    
    format = '%H:%M:%S'
    currentTime = datetime.today()
    time1 = datetime.strptime(scheduleTime, format) - datetime.strptime(str(currentTime.strftime('%H:%M:%S')), format)
    
    print(time1)


time_scheduler()

当前代码可显示设定时间与本地当前时间的时间差,但需要实现无刷屏的倒计时功能,此前用while True循环实现时会导致终端刷屏。

解决方案

要避免刷屏,核心是用\r回车符覆盖当前行输出,而非每次换行打印。同时补充处理设定时间已过当天的逻辑,确保倒计时准确:

import time
from datetime import datetime

schedule_time = input('请输入计划时间(格式:00:00:00):')
time_format = '%H:%M:%S'

def countdown():
    while True:
        current_time_str = datetime.today().strftime(time_format)
        # 转换为datetime对象计算时间差
        scheduled_dt = datetime.strptime(schedule_time, time_format)
        current_dt = datetime.strptime(current_time_str, time_format)
        
        time_diff = scheduled_dt - current_dt
        # 处理设定时间已过当天的情况,自动顺延至次日
        total_seconds = time_diff.total_seconds() if time_diff.total_seconds() >= 0 else 86400 + time_diff.total_seconds()
        
        if total_seconds <= 0:
            print('\n倒计时结束!')
            break
        
        # 转换为时分秒格式
        hours = int(total_seconds // 3600)
        minutes = int((total_seconds % 3600) // 60)
        seconds = int(total_seconds % 60)
        
        # 用\r回到行首覆盖输出,end=''避免自动换行
        print(f'\r剩余时间:{hours:02d}:{minutes:02d}:{seconds:02d}', end='')
        time.sleep(1)

countdown()

关键细节

  • \r让光标回到行首,实现单行刷新,避免终端刷屏
  • end=''阻止print自动换行,保证输出始终在同一行
  • 补充时间差为负的处理逻辑,当设定时间已过当天时,自动计算次日的倒计时
  • 每秒刷新一次时间,平衡实时性与资源占用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:25:21