最近一直在研究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. 【JAVA语法】01Java-变量与数据类型

    数据类型初阶 基本数据类型的包装类 整数类型&浮点类型&字符类型 大小类型转换 通过Scanner从控制台获取数据 变量相关基础算法 Java的错误类型 字符串String 补充-Pa ...

  2. lua中的weak table

    weakTable = {} weakTable[] = function() print("i am the first element") end weakTable[] = ...

  3. Scrum过程管理学习心得

    认识敏捷开发 在课堂上了解了瀑布开发,又在课下学习敏捷开发过程后,我发现,敏姐团队做的开发工作虽然和瀑布开发一模一样,但他们的做事方式很不一样.简单来说,两者的差别在于:瀑布开发必须先完成当前的步骤后 ...

  4. Netty入门2之----手动搭建HttpServer

    在上一章中我们认识了netty,他有三大优点:并发高,传输快,封装好.在这一章我们来用Netty搭建一个HttpServer,从实际开发中了解netty框架的一些特性和概念. netty.png 认识 ...

  5. 如何为运行的 ARM Linux 启用 LAD2.3 版本的诊断扩展

    Linux Azure Diagnostic (LAD) 扩展现在已经发布了 3.0 版本,但在 Azure 中国区,目前可用的最新版本还是 2.3. 虽然 Azure 门户提供了简单的操作版本为 L ...

  6. C# FTP删除文件以及文件夹

    1.FTP文件操作类   FtpClient using System; using System.Collections.Generic; using System.Linq; using Syst ...

  7. svn环境搭建

    (一)svn介绍   项目管理中的版本控制问题 通常软件开发由多人协作开发,如果对代码文件.文档等没有进行版本控制,将会出现很多问题: 备份多个版本,占用磁盘空间大 解决代码冲突困难 容易引发BUG ...

  8. 【Leetcode】【Medium】Construct Binary Tree from Inorder and Postorder Traversal

    Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  9. 【Leetcode】【Medium】Rotate Image

    You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). ...

  10. QT容器map的插入,修改,遍历

    除了map,QT的容器还有hash,以及迭代器等,这里写的是map #include "mainwindow.h" #include <QApplication> #i ...