为什么 Python 的多处理模块中没有 Timer 类?

编程入门 行业动态 更新时间:2024-10-27 21:25:56
本文介绍了为什么 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-28 18:22:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/736945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多处   模块   Python   Timer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!