python 可停止计划在单独的线程中

python stoppable sched in separate thread

我有一个来自 sched 模块的 python 计划,我想在一个单独的线程中执行,同时能够随时停止它。我查看了 threading module,但不知道哪个是实现它的最佳方法。

时间表示例:

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

线程中的计划示例:

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

想要的结果:

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

您描述的是可以异步停止的线程。

here所述,主要有两种方法。 其中之一是让线程代码检查某些事件(在您的示例中由 u.stop() 触发)它所做的每个操作。

另一种解决方案是强制将错误引发到某个线程中。这种方法实现起来更简单,但可能会导致意外行为,并且您的线程代码越复杂,它就越危险。

import ctypes


ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)

其中 tid 是要终止的线程。可以通过运行(在线程中)获取线程id:

print self._thread_id

在 Tomer Filiba 的 thread2 博客 post 中了解更多信息。