我有一个调用异步函数的异步 Tornado 服务器。但是,该函数只是进行一些后台处理,我不想等待它完成。我怎样才能做到这一点?这是我所拥有的示例:
@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)
最佳答案
只需删除 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”。
关于python - 不要等待异步函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25083084/