定时器在程序结束前停止执行

0 投票
1 回答
43 浏览
提问于 2025-04-12 04:20

我写了一个计时器,让它运行1分钟,然后程序才能继续,但这个计时器总是在大约12秒的时候停下来,导致程序无法继续。

我看到有人说time.sleep这个函数在系统时钟变化时可能会出问题,所以建议用time.monotonic来替代,但这样做反而让我代码出现了更多问题。

这是我写的计时器代码:

import time
import datetime


def countdown(m, s):
    total_seconds = m * 60 + s
    while total_seconds > 0:
        timer = datetime.timedelta(seconds = total_seconds)
        print(timer, end="\r")
        time.sleep(1)
        total_seconds -= 1
    if s == 5:
        print("Go!")
        print("")
    else:
        print("Alright, are you done yet? (yes/no)")

我在最后加了if语句,因为我只在两个地方用到了这个计时器:一个是倒计时五秒,另一个是一个一分钟的计时器。我想让它们在结束时打印不同的消息。我对线程不太了解,也觉得在这个程序里不需要用到它。

这是调用倒计时的代码:

if require7 == "no":
    print("Okay, I'll be nice.")
    print("(Press any key to continue)")
    input()
    print("Don't tell anybody else, but I'm giving you one minute to do those pushups.")
    input()
    print("I'll count.")
    input()
    print("Ready? I'll countdown 'till I start.")
    input()
    m = 0
    s = 5
    countdown(m, s)
    # Inputs for hours, minutes, seconds on timer
    m = 1
    s = 0
    countdown(m, s)
    input()
    if (input=="yes" or "no"):
        print("Well, sorry, but you're not eligible.")
        print("You do not have qualities that we are looking for.")
        print("Goodbye.")
    else:
        print("I don't know what you just entered, but you're not eligible.")
        print("You do not have qualities that we are looking for.")
        print("Goodbye.")

1 个回答

-1

试试这个:

import time
import datetime

def countdown(m, s):
    try:
        total_seconds = m * 60 + s
        while total_seconds > 0:
            timer = datetime.timedelta(seconds=total_seconds)
            print(f"Time remaining: {timer}", end="\r")
            time.sleep(1)
            total_seconds -= 1

        print("\nGo!")
        print("")
        response = input("Alright, are you done yet? (yes/no): ").strip().lower()
        if response == "yes":
            print("Great! You're done.")
        else:
            print("Please complete your task.")

    except ValueError:
        print("Invalid input. Please enter valid minutes and seconds.")

# Example usage:
countdown(0, 10)  # Countdown from 0 minutes and 10 seconds

输出 1:

Time remaining: 0:00:01
Go!

Alright, are you done yet? (yes/no): yes
Great! You're done.

输出 2:

Time remaining: 0:00:01
Go!

Alright, are you done yet? (yes/no): no
Please complete your task.

撰写回答