【问题标题】:Don't wait for an async function to finish不要等待异步函数完成
【发布时间】:2014-08-01 14:59:35
【问题描述】:

我有一个调用异步函数的异步龙卷风服务器。但是,该函数只是进行一些后台处理,我不想等待它完成。我怎样才能做到这一点?这是我所拥有的示例:

@gen.coroutine
def get(self):
    yield self.process('data') # I don't want to wait here
    self.write('page')

    @gen.coroutine
    def process(self, arg):
        d = yield gen.Task(self.otherFunc, arg)
        raise gen.Return(None)

【问题讨论】:

    标签: python asynchronous tornado


    【解决方案1】:

    只需在 self.process('data') 之前删除 yield。它仍然会运行,但 get 函数不会等待它完成。示例:

    @gen.coroutine
    def get(self):
        print 'a'
        yield self.process('data') # I don't want to wait here
        print 'b'
        self.write('page')
    
    @gen.coroutine
    def process(self, arg):
        print 'c'
        d = yield gen.Task(self.otherFunc, arg)
        print 'd'
        raise gen.Return(None)
    

    会给出 a,c,d,b 但是:

    @gen.coroutine
    def get(self):
        print 'a'
        self.process('data') # I don't want to wait here
        print 'b'
        self.write('page')
    
    @gen.coroutine
    def process(self, arg):
        print 'c'
        d = yield gen.Task(self.otherFunc, arg)
        print 'd'
        raise gen.Return(None)
    

    可以根据订单执行情况给出 a,c,b,d 或 a,b,c,d,但不会再等到流程完成后才能到达 'b'。

    【讨论】:

    • 请注意,如果“进程”引发异常,您将不会在任何地方记录它;将来您没有屈服,它将保持未报告的状态。考虑在调用 process() 的站点周围使用 ExceptionStackContext,以记录它引发的任何错误:tornadoweb.org/en/stable/stack_context.html
    • 在 Tornado 4.0 中,您应该使用 IOLoop.spawn_callback 来启动与其调用者上下文分离的回调。 IOLoop 将记录 Future 中包含的任何错误。 tornadoweb.org/en/stable/…
    猜你喜欢
    • 2019-06-16
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2019-11-29
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多