views:

41

answers:

3

I have a widget that measures elapsed time, then after a certain duration it does a command. However, if the widget is left I want I want it to abort this function call and not do the command.

How do I go about this?

+2  A: 

Use the threading module and start a new thread that will run the function.

Just abort the function is a bad idea as you don't know if you interrupt the thread in a critical situation. You should extend your function like this:

import threading

class WidgetThread(threading.Thread):
     def __init__(self):
         threading.Thread.__init__(self)
         self._stop = False

     def run(self):
        # ... do some time-intensive stuff that stops if self._stop ...
        #
        # Example:
        #  while not self._stop:
        #      do_somthing()

     def stop(self):
         self._stop = True



# Start the thread and make it run the function:

thread = WidgetThread()
thread.start()

# If you want to abort it:

thread.stop()
leoluk
A: 

Why not use threads and stop that? I don't think it's possible to intercept a function call in a single threaded program (if not with some kind of signal or interrupt).

Also, with your specific issue, you might want to introduce a flag and check that in the command.

Tamás Szelei
A: 

No idea about python threads, but in general the way you interrupt a thread is by having some sort of a threadsafe state object that you can set from the widget, and the logic in thread code to check for the change in state object value and break out of the thread loop.

ykaganovich