Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancellable threading.Timer in Python

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.

like image 917
Ted Avatar asked Mar 21 '12 20:03

Ted


People also ask

What is threading timer in Python?

Introduction to Python Threading Timer. The timer is a subsidiary class present in the python library named “threading”, which is generally utilized to run a code after a specified time period. Python's threading. Timer() starts after the delay specified as an argument within the threading.

How do you stop a thread execution in Python?

Using a hidden function _stop() : In order to kill a thread, we use hidden function _stop() this function is not documented but might disappear in the next version of python.

How do you delay the start of a thread in Python?

The standard way to add a time delay in Python is by calling the sleep() function from the time module. It works by suspending the execution of the calling thread for the specified number of seconds, which may be a floating-point value.


1 Answers

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() 

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() 
like image 185
Honest Abe Avatar answered Sep 21 '22 23:09

Honest Abe