为什么Python的多处理模块中没有Timer类? [英] Why no Timer class in Python's multiprocessing module?
问题描述
因此threading
模块具有从Thread
类插入的Timer
类,以重复执行某些任务.
So the threading
module has a Timer
class inhereted from Thread
class to repeatedly execute some tasks.
我想知道为什么多处理模块没有类似的TimedProcess
类,例如从Process
引入来重复执行某些任务的类?
I was wondering why doesn't the multiprocessing module have something like an analogous TimedProcess
class for e.g., which is inhereted from Process
to repeatedly execute some tasks?
可以编写这样一个定时的过程,而我已经编写了一个但仍然很好奇的过程.还是我错过了什么?
It is possible to write such a timed process and I have written one but still curious. Or am I missing something?
推荐答案
实现自己非常简单:
from multiprocessing import Process, Event
class Timer(Process):
def __init__(self, interval, function, args=[], kwargs={}):
super(Timer, self).__init__()
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
我不确定为什么stdlib中没有其中一个.也许是因为它不太可能有用?
I'm not sure why there isn't one included in the stdlib. Perhaps because its less likely to be useful?
这篇关于为什么Python的多处理模块中没有Timer类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!