动态更改@ Core.periodic方法的重复时间

时间:2016-11-02 00:33:39

标签: volttron

假设我有一个方法X,Core.periodic装饰器最初设置为60秒,有没有办法将方法X的重复时间从另一个方法改为45秒(称之为Y),而代理是运行?

class SomeAgent(Agent)
...
    @Core.periodic(settings.HEARTBEAT_PERIOD)
    method X():
       #Do stuff

    method Y():
       #Change method X's repeat time

1 个答案:

答案 0 :(得分:0)

如果要更改周期性,则必须使用self.core.periodic调用进行设置。

self.core.periodic返回对运行periodic方法的greenlet的引用。在启动新方法之前,调用kill方法来停止greenlet。您需要在启动方法中设置周期。除非您的定期函数使用消息总线,否则您将需要在其中添加一个onstart方法。

class SomeAgent(Agent):
    def __init__(self, **kwargs):
        super(SomeAgent, self).__init__(**kwargs)
        self.periodic_greenlet = None

    @Core.receiver('onstart')
    def onstart(self, sender, **kwargs):
        self.periodic_greenlet = self.core.periodic(settings.HEARTBEAT_PERIOD, self.X)


    def X(self):
       #Do stuff

    def Y(self, new_period):
       #Checking for None may seem superfluous, but there are some possible race
       #conditions at startup that cannot be completely eliminated.
       if self.periodic_greenlet is not None:
           self.periodic_greenlet.kill()

       self.periodic_greenlet = self.core.periodic(new_period, self.X)