python将时间添加到已经运行的倒计时

标签 python multithreading timer countdown

我想要一个应用程序,如果我点击一个按钮,我的倒数计时器会增加 X 的时间。

我猜我必须为此使用线程,但我不确定如何实现它。

这是我目前的代码:

def countdown_controller(add_time):
    end_it = False
    def timer(time_this):
        start = time.time()
        lastprinted = 0
        finish = start + time_this
        while time.time() < finish:
            now = int(time.time())
            if now != lastprinted:
                time_left = int(finish - now)
                print time_left
                lastprinted = now
            if end_it == True:
                now = finish
            time.sleep(0.1)
    # Check if the counter is running otherwise just add time.
    try:
        time_left 
    except NameError:
        timer(add_time)
    else:
        if time_left == 0:
        timer(add_time)
        else:
            add_this = time_left
            end_it = True
            while now != finish:
                time.sleep(0.1)
            timer(add_time + add_this)

显然这是行不通的,因为每次我调用 countdown_controller(15) fx 时,它都会开始倒计时 15 秒,如果我点击我的按钮,在计时器结束之前什么都不会发生。

帮助将不胜感激。

最佳答案

我会说代码的设计存在缺陷,因为您的屏幕输出阻止了整个程序的无所事事 (time.sleep(0.1))。

在这些情况下,通常您想要做的是在您的程序中有一个主循环,循环执行使您的程序运行的各种操作。这保证了系统资源在各种任务之间的合理分配。

在您的特定情况下,您希望在主循环中拥有的是:

  • 检查用户输入(是否添加了额外时间?)
  • 更新倒计时输出

示例实现:

import time
import curses

# The timer class    
class Timer():
    def __init__(self):
        self.target = time.time() + 5
    def add_five(self):
        self.target += 5
    def get_left(self):
        return int(self.target-time.time())

# The main program
t = Timer()
stdscr = curses.initscr()
stdscr.nodelay(True)
curses.noecho()
# This is the main loop done in curses, but you can implement it with
# a GUI toolkit or any other method you wish.
while True:
    left = t.get_left()
    if left <= 0:
        break
    stdscr.addstr(0, 0, 'Seconds left: %s ' % str(left).zfill(3))
    c = stdscr.getch()
    if c == ord('x') :
        t.add_five()
# Final operations start here
stdscr.keypad(0)
curses.echo()
curses.endwin()
print '\nTime is up!\n'

如果您按下 x 键(小写),上述程序将增加 5 秒的计数器。大多数代码是使用 curses 模块的样板,但当然,如果您使用 PyGTK、PySide 或任何其他图形工具包,它就会有所不同。

编辑: 根据经验,在 Python 中您希望尽可能避免线程化,因为它经常(但不总是)减慢程序速度(参见“Global Interpreter Lock” ) 并且因为它使软件更难调试/维护。

喂!

关于python将时间添加到已经运行的倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6688126/

相关文章:

multithreading - 等待并发线程的首选方法

java - 为什么这个 java 程序中没有竞争条件

javascript - 有没有比 setTimeout 更准确的方法来创建 Javascript 计时器?

linux - gettimeofday() 是否保证为微秒级分辨率?

python - 将嵌套字典转换为 Python 对象

python - 如何找出我的正则表达式匹配的行?

java - 并发环境下的Ehcache ReentrantReadWriteLock

python - 谷歌应用引擎/python : Can I depend on Task queue retry on failure to keep insertions to a minimum?

python - 在 seaborn 中将箱线图转换为散点图

typescript - 如何停止 rxjs 定时器