为什么 Python 的多处理模块中没有 Timer 类? [英] Why no Timer class in Python's multiprocessing module?

查看:35
本文介绍了为什么 Python 的多处理模块中没有 Timer 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以threading模块有一个Timer类继承自Thread类来重复执行一些任务.

我想知道为什么 multiprocessing 模块没有类似的 TimedProcess 类,例如从 Process 继承来重复执行某些任务?>

有可能写出这样一个定时过程,我已经写了一个,但仍然很好奇.还是我遗漏了什么?

解决方案

自己实现非常简单:

from multiprocessing import Process, Event类定时器(进程):def __init__(self, interval, function, args=[], kwargs={}):超级(定时器,自我).__init__()self.interval = 间隔self.function = 功能self.args = argsself.kwargs = kwargsself.finished = Event()定义取消(自我):"""如果定时器还没有完成就停止它"""self.finished.set()定义运行(自我):self.finished.wait(self.interval)如果不是 self.finished.is_set():self.function(*self.args, **self.kwargs)self.finished.set()

我不知道为什么标准库中没有包含一个.也许是因为它不太可能有用?

So the threading module has a Timer class inhereted from Thread class to repeatedly execute some tasks.

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?

解决方案

It's pretty straightforward to implement yourself:

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()

I'm not sure why there isn't one included in the stdlib. Perhaps because its less likely to be useful?

这篇关于为什么 Python 的多处理模块中没有 Timer 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆