您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中停止计时器后,计时器无法重新启动

在Python中停止计时器后,计时器无法重新启动

这是更正的版本:

from __future__ import print_function


from threading import Timer


def hello():
    print("Hello World!")


class RepeatingTimer(object):

    def __init__(self, interval, f, *args, **kwargs):
        self.interval = interval
        self.f = f
        self.args = args
        self.kwargs = kwargs

        self.timer = None

    def callback(self):
        self.f(*self.args, **self.kwargs)
        self.start()

    def cancel(self):
        self.timer.cancel()

    def start(self):
        self.timer = Timer(self.interval, self.callback)
        self.timer.start()


t = RepeatingTimer(3, hello)
t.start()

$ python -i foo.py
>>> Hello World!

>>> Hello World!

>>> t.cancel()
python 2022/1/1 18:31:43 有210人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶