如何在python中制作一个可暂停的计时器? [英] How to make a pausable timer in python?

查看:93
本文介绍了如何在python中制作一个可暂停的计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中创建一个具有以下功能的计时器:

timer.start() - 应该启动计时器

timer.pause() - 应该暂停计时器

timer.resume() - 应该恢复计时器

timer.get() - 应该返回当前时间

计时器应该从 0 向上运行.它用于测量时间,而不是触发回调函数.

所以如果你启动它,它应该开始像 0 1 2 3 这样的秒数,如果你暂停它,它应该静止在 3,但不会更进一步.恢复后,它会继续 4 5 6 等等

我该怎么做?

<小时>

计时器的暂停/恢复功能 不是重复的,因为我不在乎关于回调.

解决方案

# mytimer.py从日期时间导入日期时间导入时间类 MyTimer():"""timer.start() - 应该启动计时器timer.pause() - 应该暂停计时器timer.resume() - 应该恢复计时器timer.get() - 应该返回当前时间"""def __init__(self):print('初始化定时器')self.timestarted = 无self.timepaused = 无self.paused = 假定义开始(自我):""" 通过记录当前时间启动内部计时器 """打印(启动计时器")self.timestarted = datetime.now()定义暂停(自我):"""暂停计时器"""如果 self.timestarted 是 None:raise ValueError("计时器未启动")如果自我暂停:raise ValueError("定时器已经暂停")print('暂停定时器')self.timepaused = datetime.now()self.paused = Truedef简历(自我):""" 通过将暂停时间添加到开始时间来恢复计时器 """如果 self.timestarted 是 None:raise ValueError("计时器未启动")如果不是 self.paused:raise ValueError("定时器没有暂停")print('恢复定时器')pausetime = datetime.now() - self.timepausedself.timestarted = self.timestarted + 暂停时间self.paused = 假定义获取(自我):""" 返回一个显示时间量的 timedelta 对象自开始时间起经过,少了任何停顿 """print('获取定时器值')如果 self.timestarted 是 None:raise ValueError("计时器未启动")如果自我暂停:返回 self.timepaused - self.timestarted别的:返回 datetime.now() - self.timestarted如果 __name__ == "__main__":t = MyTimer()t.start()print('等待 2 秒');时间.sleep(2)打印(t.get())print('等待 1 秒');时间.睡眠(1)t.pause()print('等待 2 秒 [暂停]');时间.sleep(2)打印(t.get())print('等待 1 秒 [暂停]');时间.睡眠(1)打印(t.get())print('等待 1 秒 [暂停]');时间.睡眠(1)t.resume()print('等待 1 秒');时间.睡眠(1)打印(t.get())

运行

python mytimer.py

输出

<前>初始化定时器启动计时器等待 2 秒获取定时器值0:00:02.001523等待 1 秒暂停定时器等待 2 秒 [暂停]获取定时器值0:00:03.004724等待 1 秒 [暂停]获取定时器值0:00:03.004724等待 1 秒 [暂停]恢复定时器等待 1 秒获取定时器值0:00:04.008578

I want to create a timer in python with the following functions:

timer.start() - should start the timer

timer.pause() - should pause the timer

timer.resume() - should resume the timer

timer.get() - should return the current time

The timer should run from 0 upwards. It is meant to measure time, not trigger a callback function.

So if you start it, it should start counting the seconds like 0 1 2 3, if you pause it, it should be stilll at 3, but not going further. After its resumed it then goes on with 4 5 6 and so on

How can I do this?


Pause/Resume functions for timer is not a duplicate because I do not care about callbacks.

解决方案

# mytimer.py
from datetime import datetime
import time

class MyTimer():
    """
    timer.start() - should start the timer
    timer.pause() - should pause the timer
    timer.resume() - should resume the timer
    timer.get() - should return the current time
    """

    def __init__(self):
        print('Initializing timer')
        self.timestarted = None
        self.timepaused = None
        self.paused = False

    def start(self):
        """ Starts an internal timer by recording the current time """
        print("Starting timer")
        self.timestarted = datetime.now()

    def pause(self):
        """ Pauses the timer """
        if self.timestarted is None:
            raise ValueError("Timer not started")
        if self.paused:
            raise ValueError("Timer is already paused")
        print('Pausing timer')
        self.timepaused = datetime.now()
        self.paused = True

    def resume(self):
        """ Resumes the timer by adding the pause time to the start time """
        if self.timestarted is None:
            raise ValueError("Timer not started")
        if not self.paused:
            raise ValueError("Timer is not paused")
        print('Resuming timer')
        pausetime = datetime.now() - self.timepaused
        self.timestarted = self.timestarted + pausetime
        self.paused = False

    def get(self):
        """ Returns a timedelta object showing the amount of time
            elapsed since the start time, less any pauses """
        print('Get timer value')
        if self.timestarted is None:
            raise ValueError("Timer not started")
        if self.paused:
            return self.timepaused - self.timestarted
        else:
            return datetime.now() - self.timestarted

if __name__ == "__main__":
    t = MyTimer()
    t.start()
    print('Waiting 2 seconds'); time.sleep(2)
    print(t.get())
    print('Waiting 1 second'); time.sleep(1)
    t.pause()
    print('Waiting 2 seconds [paused]'); time.sleep(2)
    print(t.get())
    print('Waiting 1 second [paused]'); time.sleep(1)
    print(t.get())
    print('Waiting 1 second [paused]'); time.sleep(1)
    t.resume()
    print('Waiting 1 second'); time.sleep(1)
    print(t.get())

Run

python mytimer.py

Output

Initializing timer
Starting timer
Waiting 2 seconds
Get timer value
0:00:02.001523
Waiting 1 second
Pausing timer
Waiting 2 seconds [paused]
Get timer value
0:00:03.004724
Waiting 1 second [paused]
Get timer value
0:00:03.004724
Waiting 1 second [paused]
Resuming timer
Waiting 1 second
Get timer value
0:00:04.008578

这篇关于如何在python中制作一个可暂停的计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆