zoukankan      html  css  js  c++  java
  • twisted——scheduling tasks

    如果我们想在reactor开始后,能执行一些方法,可以使用reactor.callLater()方法和twisted.internet.task中的方法。

    1、使用reactor.callLater()

    calllater.py

    1 from twisted.internet import reactor
    2 
    3 def fun(s):
    4     print "3 seconds later %s" % s
    5     reactor.stop()
    6 
    7 reactor.callLater(3, fun, "ha!")
    8 reactor.run()

    2、如果我们需要使用到方法返回的数据,那么就需要借用task.deferLater()方法,它将会生成Defered,并且建立延迟调用。

    deferlater.py

     1 from twisted.internet import task, reactor
     2 
     3 def f(s):
     4     reactor.stop()
     5     return "3 seconds later %s " % s
     6     
     7 
     8 d=task.deferLater(reactor, 3, f, 'ha!')
     9 
    10 def called(result):
    11     print result
    12     # reactor.stop()
    13 
    14 d.addCallback(called)
    15 
    16 reactor.run()

    3、如果我们想重复的调用某一个方法,可以使用task.LoopingCall()方法。

    1 def runEverySecond():
    2     print "a second has passed"
    3 
    4 l=task.LoopingCall(runEverySecond)
    5 l.start(1.0)
    6 
    7 reactor.run()

    如果我们需要取消任务。

    1 def f():
    2     print "I would't run .. "
    3 
    4 callID=reactor.callLater(5, f)
    5 callID.cancel()
    6 reactor.run()

    需要注意的是,我们要想那些任务能够执行,则必须通过reactor.run()来开始。

  • 相关阅读:
    关于表单(一)
    HTML基础
    Spider -- MySQL数据库 之 增量爬取
    Spider -- 多级页面 爬取
    Spider -- 数据持久化 之 MongoDB
    Spider -- 数据持久化 之 MySQL
    Spider -- 乱码解决方案 Windows系统下
    Spider -- 数据持久化 之 csv文件
    Spider -- 常规 爬取网站 步骤
    Spider -- re 正则解析模块
  • 原文地址:https://www.cnblogs.com/lazyzhong/p/3918592.html
Copyright © 2011-2022 走看看