python - 如何中断或取消 SimPy 超时事件?

标签 python simulation simpy

我想创建一个带有回调的计时器,该回调可以使用 SimPy 中断或重置。如果中断,我不想执行回调,如果重置,我希望计时器以与 env.now 相同的延迟重新启动。最初,这似乎是一件简单的事情,只需使用 env.timeout 即可。但是,文档说明:

To actually let time pass in a simulation, there is the timeout event. A timeout has two parameters: a delay and an optional value: Timeout(delay, value=None). It triggers itself during its creation and schedules itself at now + delay. Thus, the succeed() and fail() methods cannot be called again and you have to pass the event value to it when you create the timeout.

因为模拟开始被触发,我不能添加回调,因为你不能调用fail,我不能中断超时。

我考虑过只实现一个等待一个时间步长的进程,如果它被中断或到达它正在等待的 env.now 则检查一个标志,但这似乎非常低效,如果我有很多计时器(我会的),我担心发电机的数量会压倒模拟。 (超时功能似乎通过在模拟的 future 安排自己来工作,这就是为什么你可以有大量的人跑来跑去)。

因此规范是 - 创建一个在指定时间后触发回调的事件,但可以在该时间发生之前重置或中断。有什么想法吗?

最佳答案

好吧,如果我正确理解了你的问题,你可以做的一件事是创建一个 Timer 类,它带有一个检查 simpy.Interrupt 的等待方法。您可以实现 stop(),这样当它被调用时,您也可以调用 interrupt()。这样,只要先前调用了 interrupt(),就不会执行回调。重置方法将简单地再次调用 stop()(中断)和 start(),从而将操作设置回 running() 并调用 wait() 再次,允许在每次超时后再次执行回调,直到再次调用中断。

下面是此类 Timer 类的示例实现:

import simpy

class Timer(object):

    def __init__(self, env, delay, callback):
        self.env      = env 
        self.delay    = delay
        self.action   = None
        self.callback = callback
        self.running  = False
        self.canceled = False

    def wait(self):
        """
        Calls a callback after time has elapsed. 
        """
        try:
            yield self.env.timeout(self.delay)
            self.callback()
            self.running  = False
        except simpy.Interrupt as i:
            print "Interrupted!"
            self.canceled = True
            self.running  = False

    def start(self):
        """
        Starts the timer 
        """
        if not self.running:
            self.running = True
            self.action  = self.env.process(self.wait())

    def stop(self):
        """
        Stops the timer 
        """
        if self.running:
            self.action.interrupt()
            self.action = None

    def reset(self):
        """
        Interrupts the current timer and restarts. 
        """
        self.stop()
        self.start()

关于python - 如何中断或取消 SimPy 超时事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35202982/

相关文章:

python - 离散事件建模 - Simpy - 如何建模复杂的依赖关系?

python - 使用python simpy实时模拟电池充电

python - 如何在 Python 中实现向量自回归?

python - 当 Numpy/Scipy 指针被复制到局部变量时会发生什么?

c - 数组会用在什么地方?

math - 板球物理,基本模拟

grid - 网格/仓库布局上离散事件模拟的可视化

python - 创建一个带有链接的矩阵

python - 自动粘贴创建 -t plone3_buildout

c++ - 在 C++11 中模拟类似 Arduino 的中断