Bazaka  Bazaka
Bazaka Bazaka

Reputation: 135

Threading.Times doesn't work

I have a problem with Timer in Threading

From documentation:

 def hello():
    print "hello, world"
    t = Timer(30.0, hello)   
    t.start() # after 30 seconds, "hello, world" will be printed

cancel()

Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.

Here is my code:

def function_terminate():
        raise Exception

def do():
    thr = threading.Timer(5.0, function_terminate(), args=())
    thr.start()
    sleep(2)
    thr.cancel()

This code throws Exception

But according to the documentation, function_terminate() method must be run after 5 sec after calling. Since, I have thr.cancel after 2 seconds (sleep(2)), thread must be cancel and Exception will never throw

What's wrong in my code?

Upvotes: 2

Views: 624

Answers (1)

kecer
kecer

Reputation: 3141

You are not passing the function as an argument, you are calling it.

This

thr = threading.Timer(5.0, function_terminate(), args=())

has to become this

thr = threading.Timer(5.0, function_terminate, args=())

In your case, you were passing return value of function_terminate (None), not the function alone.

Upvotes: 3

Related Questions