龙卷风PeriodicCallback立即执行

时间:2018-04-27 08:33:28

标签: python tornado

我想每10分钟刷一个对象,所以我使用tornado.ioloop.PeriodicCallback(myjob, 10*60*1000)但是第一次执行是10分钟后。是否有一些设置让myjob 0分钟,10分钟,20分钟时运行.....?

class Store(object):
    def __init__(self):
        self.data = None

    @tornado.gen.coroutine
    def load(self):
        with (yield STORE_POOL.connected_client()) as client:
            data = yield client.call("HGETALL", self.static_dict_key)
            self.data = {data[i].decode("utf-8"): int(data[i + 1]) for i in range(0, len(data), 2)}


def main():
    ...
    store = Store()
    # ----> Do i need to add some code here? [1]
    backjob = tornado.ioloop.PeriodicCallback(store.load, BACKJOB_TIME)
    backjob.start()

我需要在[1]中添加一些代码吗? 我想会有2个计划:
1 GT;更改PeriodicCallback()中的某些设置 2 - ;在PeriodicCallback()之前执行一次store.load但是我不知道如何只与@tornado.gen.coroutine同步运行一次作业。

1 个答案:

答案 0 :(得分:0)

这很常见,我为方便起见编写了类似的功能。这是添加可变定时执行的简单方法:

from tornado import ioloop

class VariableFire(object):

    def __init__(self, max_delay, increment_by):
        """
        :param max_delay: Max number of seconds.
        :param increment_by: Increment delay per interval until max is hit.
        """
        self.max_delay = max_delay
        self.increment_by = increment_by
        self.delay = 1

    def fire(self, fn, *args, **kwargs):
        # execute
        fn(*args, **kwargs)

        # get the delay interval
        delay = self.delay

        if self.delay < self.max_delay:
            # increment the delay by certain amount
            self.delay += self.increment_by
        elif delay > self.max_delay:
            # reset value to max_delay
            self.delay = delay = self.max_delay

        ioloop.IOLoop.current().call_later(delay, self.fire, fn, *args, **kwargs)


variable = VariableFire(max_delay = 30, increment_by = 3)
variable.fire(print, 'Hello World')

ioloop.IOLoop.current().start()

如果你很聪明,你可以把它变成装饰者并直接在函数上使用它,但为了简单起见......

  

1&GT;更改PeriodicCallback()中的一些设置。

无法使用PeriodicCallback进行操作,但在我的示例中,您可以稍后更改间隔。

  

2 - ;在PeriodicCallback()之前执行一次store.load但是我没有   关于如何与@ tornado.gen.coroutine同步运行工作的想法   只有一次。

如果你决定使用类似于我的例子的代码,你可以运行:

variable.fire(store.load)