Hugo Trentesaux
Hugo Trentesaux

Reputation: 1999

python stoppable sched in separate thread

I have a python schedule from sched module that I want to execute in a separate thread while being able to stop it at any moment. I looked the threading module but do not know which is the best approach to implement this.

example of the schedule:

>>> s.run()
one
two
three
end

example of the schedule in a thread:

>>> t = threading.Thread(target = s.run)
>>> t.start()
one
two
>>> print("ok")
ok
three
end
>>>

wanted result:

>>> u = stoppable_schedule(s.run)
>>> u.start()
>>>
one
two
>>> u.stop()
"schedule stopped"

Upvotes: 0

Views: 71

Answers (1)

Gabriel Fernandez
Gabriel Fernandez

Reputation: 650

What you are describing are threads that can be asynchronously stopped.

As described here, there are two main approaches. One of them is to have the thread code check for some event (triggered by u.stop() in your example) every operation it makes.

The other solution is to force raise an error into some thread. This approach is simpler to implement, but may cause unexpected behavior and the more complex your thread code is, the more dangerous it gets.

import ctypes


ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)

Where tid is the the thread to be terminated. You can get the thread id by running (in the thread):

print self._thread_id

More info about that in the thread2 blog post by Tomer Filiba.

Upvotes: 1

Related Questions