聊聊python libev事件库的定时器调度

libev 是个比libevent更加简洁的事件库,python的gevent就是使用libev来实现的。  pyev是libev的python封装版本。 下面是个pyev的定时器例子。 

import signal
import pyev


def sig_cb(watcher, revents):
    print("got SIGINT")
    loop = watcher.loop
    # optional - stop all watchers
    if loop.data:
        print("stopping watchers: {0}".format(loop.data))
        while loop.data:
            loop.data.pop().stop()
    # unloop all nested loop
    print("stopping the loop: {0}".format(loop))
    loop.stop(pyev.EVBREAK_ALL)


def timer_cb(watcher, revents):
    watcher.data += 1
    print("timer.data: {0}".format(watcher.data))
    print("timer.loop.iteration: {0}".format(watcher.loop.iteration))
    print("timer.loop.now(): {0}".format(watcher.loop.now()))


if __name__ == "__main__":
    loop = pyev.default_loop()
    # initialise and start a repeating timer
    timer = loop.timer(0, 2, timer_cb, 0)
    timer.start()
    # initialise and start a Signal watcher
    sig = loop.signal(signal.SIGINT, sig_cb)
    sig.start()
    loop.data = [timer, sig] # optional
    # now wait for events to arrive
    loop.start()

一般成熟的事件库都会实现timer跟periodic功能点,pyev也不例外。

timer类型

#xiaorui.cc
Timer — Timer watcher
    class pyev.Timer(after, repeat, loop, callback[, data=None, priority=0])
    Parameters: 
    after (float) – configure the timer to trigger after after seconds.
    repeat (float) – If repeat is 0.0, then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.
    loop (Loop) – loop object responsible for this watcher (accessible through Watcher.loop).
    callback (callable) – See Watcher.callback.
    data (object) – any Python object you might want to attach to the watcher (stored in Watcher.data).
    priority (int) – See Watcher.priority.

Periodic类型

#xiaorui.cc

Periodic — Periodic watcher
    class pyev.Periodic(offset, interval, loop, callback[, data=None, priority=0])
    Parameters: 
    offset (float) – See Periodic modes of operation.
    interval (float) – See Periodic modes of operation.
    loop (Loop) – loop object responsible for this watcher (accessible through Watcher.loop).
    callback (callable) – See Watcher.callback.
    data (object) – any Python object you might want to attach to the watcher (stored in Watcher.data).
    priority (int) – See Watcher.priority.

先留个地…  过段时间给大家聊聊pyev的实现细节。 


大家觉得文章对你有些作用! 如果想赏钱,可以用微信扫描下面的二维码,感谢!
另外再次标注博客原地址  xiaorui.cc

发表评论

邮箱地址不会被公开。 必填项已用*标注