Tornado PeriodicCallback在上执行

2024-09-30 01:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想每10分钟刷新一次对象,所以我使用tornado.ioloop.PeriodicCallback(myjob, 10*60*1000),但是第一次执行是在10分钟之后。是否有设置使myjob0分钟、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]中添加一些代码吗?
我想有两个计划:
1>;更改PeriodicCallback()中的某些设置。
2>;执行存储.加载在PeriodicCallback()之前一次,但我不知道如何与@tornado.gen.coroutine同步运行一次作业。在


Tags: storeselfclientdatadefloadtornadogen
1条回答
网友
1楼 · 发布于 2024-09-30 01:30:28

这很常见,为了方便起见,我编写了类似的函数。以下是添加可变时间执行的简单方法:

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> change some setting in PeriodicCallback().

PeriodicCallback无法做到这一点,但在我的示例中,您可以在以后更改间隔。在

2> execute store.load once before PeriodicCallback() BUT I have no idea about how to run a job synchronously with @tornado.gen.coroutine only once.

如果您决定使用与我的示例类似的代码,您只需运行:

^{pr2}$

相关问题 更多 >

    热门问题