Python 中的可取消 threading.Timer [英] Cancellable threading.Timer in Python

查看:58
本文介绍了Python 中的可取消 threading.Timer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个倒计时到给定时间的方法,除非给出重新启动命令,否则它将执行任务.但我不认为 Python threading.Timer 类允许计时器被取消.

I am trying to write a method that counts down to a given time and unless a restart command is given, it will execute the task. But I don't think Python threading.Timer class allows for timer to be cancelable.

import threading

def countdown(action):
    def printText():
        print 'hello!'

    t = threading.Timer(5.0, printText)
    if (action == 'reset'):
        t.cancel()

    t.start()

我知道上面的代码不知何故是错误的.非常感谢这里的一些指导.

I know the above code is wrong somehow. Would appreciate some kind guidance over here.

推荐答案

你会在启动计时器后调用取消方法:

You would call the cancel method after you start the timer:

import time
import threading

def hello():
    print "hello, world"
    time.sleep(2)

t = threading.Timer(3.0, hello)
t.start()
var = 'something'
if var == 'something':
    t.cancel()

您可能会考虑在 上使用 while 循环线程,而不是使用定时器.
以下是 Nikolaus Gradwohl 对另一个问题的答案的示例:

You might consider using a while-loop on a Thread, instead of using a Timer.
Here is an example appropriated from Nikolaus Gradwohl's answer to another question:

import threading
import time

class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.count = 10

    def run(self):
        while self.count > 0 and not self.event.is_set():
            print self.count
            self.count -= 1
            self.event.wait(1)

    def stop(self):
        self.event.set()

tmr = TimerClass()
tmr.start()

time.sleep(3)

tmr.stop()

这篇关于Python 中的可取消 threading.Timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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