twisted reactor calllater实现

1.      calllater实现代码

测试源码:

from twisted.internet import reactor
from twisted.internet import defer

def func_1():
    print('calllater测试')
    time.sleep(5)
    print('calllater结束')

# error handle
def test_deferred_a():
    #d = test_retrurn_deferred()
   
reactor.callLater(4, func_1)
   
reactor.callLater(15, reactor.stop)
    reactor.run() if __name__ == '__main__':
    test_deferred_a()

1.1.    第一步:调用calllater

reactor.callLater(3, d.callback, 8)

先找到calllater

# <twisted.internet.selectreactor.SelectReactor object at 0x000000CE3BFC72B0>
@implementer(IReactorCore, IReactorTime,
IReactorPluggableResolver,
            
IReactorPluggableNameResolver, _ISupportsExitSignalCapturing)
class ReactorBase(object):
    """
    Default base class for Reactors.
    """
   
def callLater(self,
_seconds, _f, *args, **kw):
        """See
twisted.internet.interfaces.IReactorTime.callLater.
        """
       
assert callable(_f), "%s
is not callable"
% _f
        assert _seconds
>= 0, \
               "%s
is not greater than or equal to 0 seconds"
% (_seconds,)
        tple = DelayedCall(self.seconds()
+ _seconds, _f, args, kw,
                           self._cancelCallLater,
                           self._moveCallLaterSooner,
                           seconds=self.seconds)
        self._newTimedCalls.append(tple)
        return tple

DelayedCall基本上可以把它当作一个中间类,用于保存一些信息。

结果就是向self._newTimedCalls添加一个定时调用

self._newTimedCalls.append(tple)

可以看一下它的具体内容

_newTimedCalls= <class 'list'>:
[<twisted.internet.base.DelayedCall object at 0x000000CE3C2EA668>]

1.2.   
第二步

reactor.run()

跳过一些前置处理内容,直接到mainloop

def mainLoop(self):
    while self._started:
        try:
            while self._started:
                # Advance
simulation time in delayed event
                # processors.
               
self.runUntilCurrent()
                t2 = self.timeout()
                t = self.running and t2
                self.doIteration(t)
        except:
            log.msg("Unexpected
error in main loop."
)
            log.err()
        else:
            log.msg('Main loop
terminated.'
)

进入self.runUntilCurrent()

def runUntilCurrent(self):
    """

        运行所有挂起的calls
    Run all pending timed calls.
    """
   
if self.threadCallQueue:
        # Keep track of how
many calls we actually make, as we're
        # making them, in case another
call is added to the queue
        # while we're in this loop.
        
count = 0
        total = len(self.threadCallQueue)
        for (f, a,
kw) in self.threadCallQueue:
            try:
                f(*a, **kw)
            except:
                log.err()
            count += 1
            if count ==
total:
                break
        del
self.threadCallQueue[:count]
        if self.threadCallQueue:
            self.wakeUp()

# insert new delayed
calls now
   
self._insertNewDelayedCalls()

now = self.seconds()
while self._pendingTimedCalls and (self._pendingTimedCalls[0].time
<= now):
    call = heappop(self._pendingTimedCalls)
    if call.cancelled:
        self._cancellations-=1
        continue

if call.delayed_time
> 0:
        call.activate_delay()
        heappush(self._pendingTimedCalls,
call)
        continue

try:
        call.called = 1
        call.func(*call.args,
**call.kw)
    except:
        log.deferr()
        if hasattr(call, "creator"):
            e = "\n"
           
e += " C:
previous exception occurred in "
+ \
                 "a DelayedCall
created here:
\n"
           
e += "
C:"
           
e += "".join(call.creator).rstrip().replace("\n","\n C:")
            e += "\n"
           
log.msg(e)

if (self._cancellations > 50 and
    
self._cancellations
> len(self._pendingTimedCalls) >> 1):
    self._cancellations
= 0
    self._pendingTimedCalls
= [x for x in self._pendingTimedCalls
                               if not x.cancelled]
    heapify(self._pendingTimedCalls)

if self._justStopped:
    self._justStopped
= False
   
self.fireSystemEvent("shutdown")

进入self._insertNewDelayedCalls()

def _insertNewDelayedCalls(self):
    for call in self._newTimedCalls:
        if call.cancelled:
            self._cancellations-=1
        else:
            call.activate_delay()
            heappush(self._pendingTimedCalls,
call)
    self._newTimedCalls
= []

从self._newTimedCalls中获取DelayedCall()实例,放入self._pendingTimedCalls

在runUntilCurrent中会调用self._pendingTimedCallsk列表相关对象,也就是执行func_1.

2.     
其它

2.1.   
代码解析1

heappush(self._pendingTimedCalls,
call)

函数heappush源自heapq.py

def heappush(heap, item):
    """Push
item onto heap, maintaining the heap invariant."""
   
heap.append(item)
    _siftdown(heap, 0, len(heap)-1)

简单点说,它会构建一个有序堆,默认最小堆。

在构建有序堆过程中肯定是要比较int类型了,但call是一个类。

这里要回顾python类的特殊方法了,已有文档,不赘述。

call是DelayedCall类的实例,查看相关代码。

def __le__(self, other):
    """
    Implement C{<=} operator between
two L{DelayedCall} instances.

Comparison is based on the C{time}
attribute (unadjusted by the
    delayed time).
    """
   
return self.time
<= other.time

def __lt__(self, other):
    """
    Implement C{<} operator between
two L{DelayedCall} instances.

Comparison is based on the C{time}
attribute (unadjusted by the
    delayed time).
    """
   
return self.time
< other.time

twisted reactor calllater实现的更多相关文章

  1. (三)认识twisted reactor

    一.reactor是单线程模型,简单粗暴,也就是说网络IO和我们的业务逻辑一般是在一个线程里,其中网络IO通过event loop的方式去异步执行,效率也很高.看下官网的这幅图,比较清晰 twiste ...

  2. twisted reactor分析

    调用reactor.run(),就会调用到mainloop函数,从而调用到select或epoll,监控fd的读写. posixbase.py: def listenTCP(self, port, f ...

  3. twisted reactor 实现源码解析

    twisted reactor 实现源码解析 1.      reactor源码解析 1.1.    案例分析代码: from twisted.internet import protocol fro ...

  4. twisted reactor执行流程

    #reactorbase的主循环 def mainLoop(self): while self._started: try: while self._started: # Advance simula ...

  5. Python Twisted、Reactor

    catalogue . Twisted理论基础 . 异步编程模式与Reactor . Twisted网络编程 . reactor进程管理编程 . Twisted并发连接 1. Twisted理论基础 ...

  6. 理解twisted中的reactor和deferred(二)

    Deferred可以添加多个回调函数,每个回调函数的结果作为下一个回调函数的参数 代码实例(可在pycharm中运行,摘自 https://twistedmatrix.com/documents/cu ...

  7. 理解twisted中的reactor和deferred(一)

    Deferred是一个延迟加载对象,这个概念类似于tornado future,是调用异步操作返回的一个对象,其中包括了操作成功后的回调处理,错误后的回调处理. 简单讲,当我们需要执行一个耗时操作,比 ...

  8. 笔记-twisted源码-import reactor解析

    笔记-twisted源码-import reactor解析 1.      twisted源码解析-1 twisted reactor实现原理: 第一步: from twisted.internet ...

  9. Python中reactor,factory,protocol

    最为简单的情况下,除了了解清reactor的简单使用,你还要了解Protocol和Factory.它们最终都会由reactor的侦听建立和run来统一调度起来. 建立服务器的第一个要解决的问题就是服务 ...

随机推荐

  1. html表单提交给PHP然后浏览器显示出了PHP的源代码

    今天学习到PHP处理网页表单提交的数据时,碰到一个巨头疼的问题,先贴上案例代码: html表单部分: <html> <head> <meta charset=" ...

  2. wamp配置本地多站点。

    ' 进入C:\wamp64\wamp64\bin\apache\apache2.4.37\conf\http.conf 首先确保httpd-vhosts.conf扩展文件引入进来了,部分版本默认是不引 ...

  3. 网站调用qq第三方登录

    1. 准备工作 (1) 接入QQ登录前,网站需首先进行申请,获得对应的appid与appkey,以保证后续流程中可正确对网站与用户进行验证与授权. ① 注册QQ互联开发者账号  网址  https:/ ...

  4. WIN10 设置WEB

    Web服务器搭建步骤(Win10) 1.在“开始”菜单处打开“控制面板”. 2点击“程序”. 3.点击“启动或关闭Windows功能”. 4.对“Internet Information Servic ...

  5. Java进阶学习(4)之继承与多态(上)

    继承 媒体资料库的设计 代码复制是质量不良的表现 不具有可扩展性和可维护性 继承 子类父类关系 子类继承了什么 先定义初始化,后构造器 子类和父类的关系 子类有变量和父类变量相同时,父类变量隐藏 父类 ...

  6. spring controller中默认转发、forward转发、redirect转发之间的区别

    默认转发 @RequestMapping("/123") public String test(HttpSession session) { System.out.println( ...

  7. 推荐几个c/c++语言编写的游戏源码下载网站

    在游戏开发的学习或工作中,利用完好的游戏源码可以事半功倍,不仅可以逆向学习开拓思维,也可以大大减少设计周期.自己浏览了很游戏源码下载的网站,发现大多数质量都良莠不齐,且大部分需要消费才能下载,下面整理 ...

  8. js处理文章详情页点击量统计

    具体需求:在文章管理系统中,需要统计文章详情页面的点击量,来体现该文章是否受用户欢迎,方便管理员调整日后编辑新文章时的内容方向. 解决方案:设置有过期时间的cookie 我们在访问文章详情页面时,拿到 ...

  9. 一个c程序的执行是从什么开始的?

    一个C语言的执行是从本程序的main函数开始,到main函数结束,但需要注意的是,也是有特殊情况的,若是代码中出现了exit函数,则直接结束程序,对于这一点还是需要了解的. 关于c语言需要了解的是,C ...

  10. P & R 9

    Floorplan: 要做好floorplan需要掌握哪些知识跟技能? 明确Floorplan 处理的对象:对于数字设计的 Floorplan 来说,它是一个很依赖前后步骤的一个过程,这个可以看作是后 ...