跑在龙卷风异步后台任务 [英] Running an async background task in Tornado

查看:145
本文介绍了跑在龙卷风异步后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读旋风文档,这是非常清楚如何调用一个异步函数返回的响应:

Reading the Tornado documentation, it's very clear how to call an async function to return a response:

class GenAsyncHandler(RequestHandler):
    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch("http://example.com")
        do_something_with_response(response)
        self.render("template.html")

什么欠缺的是应该如何调用被异步作出一个没有关联到当前请求的后台任务:

What's lacking is how should a call be made asynchronously to a background task that has no relevance to the current request:

class GenAsyncHandler(RequestHandler):
    @gen.coroutine
    def _background_task():
        pass  # do lots of background stuff

    @gen.coroutine
    def get(self):
        _dont_care = yield self._background_task()
        self.render("template.html")

这code,预计将正常工作,但它同步运行,直到它完成它的要求等待。

This code would be expected to work, except that it runs synchronously and the request waits on it until it's finished.

什么是的右键的方式来异步调用这项任务,同时立即返回当前请求?

What is the right way to asynchronously call this task, while immediately returning the current request?

推荐答案

不幸的是它是一种比较棘手。您需要既脱离当前请求的后台任务(以便在后台任务失败不会扔到请求一个随机的异常结果),并确保的的东西的是听背景任务的结果(以记录其错误,如果没有别的)。这意味着像这样:

Unfortunately it's kind of tricky. You need to both detach the background task from the current request (so that a failure in the background task doesn't result in a random exception thrown into the request) and ensure that something is listening to the background task's result (to log its errors if nothing else). This means something like this:

from tornado.ioloop import IOLoop
from tornado.stack_context import run_in_stack_context, NullContext
IOLoop.current().add_future(run_in_stack_context(NullContext(), self._background_task),
                            lambda f: f.result())

像这样的东西可能会被加入到龙卷风本身的未来。

Something like this will probably be added to tornado itself in the future.

更新:由于旋风4.0,上述功能可在的 IOLoop.spawn_callback 方法。

Update: Since Tornado 4.0, the above functionality is available in the IOLoop.spawn_callback method.

这篇关于跑在龙卷风异步后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆