最近一直在研究Tornado异步操作,然而一番研究后发现要使一个函数异步化的最好方法就是采用相关异步库,但目前很多功能强大的库都不在此列。经过一番查找文档和搜索示范,终于发现了ThreadPoolExecutor模块和run_on_executor装饰器。用法就是建立线程池,用run_on_executor装饰的函数即运行在其中线程中,从而从主线程中分离出来,达到异步的目的。
另外,Tornado的IOLoop实例还有IOLoop.add_callback(callback, *args, **kwargs)方法,文档中的描述如下:

Calls the given callback on the next I/O loop iteration.
It is safe to call this method from any thread at any time, except from a signal handler. Note that this is the only method in IOLoop that makes this thread-safety guarantee; all other interaction with theIOLoop must be done from that IOLoop‘s thread. add_callback() may be used to transfer control from other threads to the IOLoop‘s thread.

意思就是在执行add_callback方法后马上就会执行下一行代码,而callback函数将在下一轮事件循环中才调用,从而就能实现延迟任务。在Web APP中应付HTTP请求时,当有一些耗时操作并不需要返回给请求方时,就可以采用延迟任务的形式,比如发送提醒邮件。
示范代码如下:

#!/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import tornado.gen
from tornado.concurrent import run_on_executor
# 这个并发库在python3自带;在python2需要安装sudo pip install futures
from concurrent.futures import ThreadPoolExecutor
import time
from tornado.options import define, options
define("port", default=8002, help="run on the given port", type=int) class SleepHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(2) def get(self):
tornado.ioloop.IOLoop.instance().add_callback(self.sleep) # 这样将在下一轮事件循环执行self.sleep
self.write("when i sleep") @run_on_executor
def sleep(self):
time.sleep(5)
print("yes")
return 5 if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[
(r"/sleep", SleepHandler), ])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()

小礼物走一走,来简书关注我

作者:不问喂神马
链接:https://www.jianshu.com/p/3d20a092588d
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

Tornado异步与延迟任务的更多相关文章

  1. tornado异步请求的理解(转)

    tornado异步请求的理解 http://www.kankanews.com/ICkengine/archives/88953.shtml 官网第一段话: Tornado is a Python w ...

  2. 使用Tornado异步接入第三方(支付宝)支付

    目前国内比较流行的第三方支付主要有支付宝和微信支付,博主最近研究了下如何用Python接入支付宝支付,这里我以Tornado作为web框架,接入支付宝构造支付接口. 使用Tornado异步接入支付宝支 ...

  3. Tornado异步非阻塞的使用以及原理

    Tornado 和现在的主流 Web 服务器框架(包括大多数 Python 的框架)有着明显的区别:它是非阻塞式服务器,而且速度相当快.得利于其 非阻塞的方式和对 epoll 的运用,Tornado ...

  4. Python Web框架 tornado 异步原理

    Python Web框架 tornado 异步原理 参考:http://www.jb51.net/article/64747.htm 待整理

  5. Tornado异步(2)

    Tornado异步 因为epoll主要是用来解决网络IO的并发问题,所以Tornado的异步编程也主要体现在网络IO的异步上,即异步Web请求. 1. tornado.httpclient.Async ...

  6. tornado异步(1)

    1. 同步 我们用两个函数来模拟两个客户端请求,并依次进行处理: # coding:utf-8 def req_a(): """模拟请求a""&quo ...

  7. tornado异步请求响应速度的实例测试

    tornado异步请求响应速度的实例测试

  8. 5.(基础)tornado异步

    终于到了传说中的异步了,感觉异步这个名字听起来就很酷酷的,以前还不是多擅长Python时,就跑去看twisted的源码,结果给我幼小的心灵留下了创伤.反正包括我在内,都知道异步编程很强大,但是却很少在 ...

  9. Python web框架 Tornado异步非阻塞

    Python web框架 Tornado异步非阻塞   异步非阻塞 阻塞式:(适用于所有框架,Django,Flask,Tornado,Bottle) 一个请求到来未处理完成,后续一直等待 解决方案: ...

随机推荐

  1. Maven 安装与使用(一)

    1. 安装 参考:http://maven.apache.org/install.html A. win7环境下,官网下载maven安装文件 B. 解压缩maven文件 C. 确认已配置好JAVA环境 ...

  2. Glide实现查看图片和保存图片到手机

    两种方式, 推荐方式一 方式一 downloadOnly 创建一个 ImageActivity public class ImageActivity extends AppCompatActivity ...

  3. eclipse安装checkStyle

    今天用eclipse mars 安装checkstyle 代码测试工具,安装完后重启竟然没有,最后发现原来是 自己安装的步骤错了,记录下. 1. 我的版本是:Version: Mars.2 Relea ...

  4. Windows IO 性能简单测试

    转自:http://bbs.csdn.net/topics/360111289, 有改动. #include <windows.h> #include <stdio.h> #i ...

  5. PHP通过header和meta实现页面编码声明

    一.使用方式: <META http-equiv=”content-type” content=”text/html; charset=xxx”> header(“content-type ...

  6. 【Leetcode】【Medium】4Sum

    Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...

  7. easyui学习笔记6—基本的Accordion(手风琴)

    手风琴也是web页面中常见的一个控件,常常用在网站后台管理中,这里我们看看easyui中基本的手风琴设置. 1.先看看引用的资源 <meta charset="UTF-8" ...

  8. 使用BAPISDORDER_GETDETAILEDLIST创建S/4HANA的Outbound Delivery

    要在S/4HANA里创建Outbound Delivery,首先要具有一个销售订单,ID为376,通过事务码VA03查看. 只用61行代码就能实现基于这个Sales Order去创建对应的outbou ...

  9. Linux-python的一些小问题

    1.python版本和pip版本 2.PATH和PYTONPATH 1.python版本和pip版本 1.python版本 一般Ubuntu里面都装的不止一个版本的python,比如有python2. ...

  10. UML用例图间关系说明

    用例间一般存在如下四种关系: 1."通信"关系(<<cmmunicate>>构造型): "通信"关系:使用实心的关联线或带<< ...