zoukankan      html  css  js  c++  java
  • python框架---->APScheduler的使用

      这里介绍一下python中关于定时器的一些使用,包括原生的sche包和第三方框架APScheduler的实现。流年未亡,夏日已尽。种花的人变成了看花的人,看花的人变成了葬花的人。

    python中的sche模块

    python中的sch有模块提供了定时器任务的功能,在3.3版本之后sche模块里面的scheduler类在多线程的环境中是安全的。以下是一个案例

    import sched, time
    
    sche = sched.scheduler(time.time, time.sleep)
    
    def print_time(a='default'):
        print('From print_time', time.time(), a)
    
    def print_some_time():
        print(time.time())
        # 10是delay单位是毫秒, 1代表优先级
        sche.enter(10, 1, print_time)
        sche.enter(5, 2, print_time, argument=('positional',))
        sche.enter(5, 1, print_time, kwargs={'a': 'keyword'})
        sche.run()
        print(time.time())
    
    print_some_time()

    运行的打印结果如下:

    1511139390.598038
    From print_time 1511139395.5982432 keyword
    From print_time 1511139395.5982432 positional
    From print_time 1511139400.5984359 default
    1511139400.5984359

    查看scheduler.enter的源码,可以看到它实际调用的是enterabs方法。

    def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
        """A variant that specifies the time as a relative time.
    
        This is actually the more commonly used interface.
    
        """
        time = self.timefunc() + delay
        return self.enterabs(time, priority, action, argument, kwargs)

    而对于enterabs方法的argument和kwargs的含义,官方文档的解释如下:它们可以作为action的参数,也就是上述例子中的print_time方法的参数

    argument is a sequence holding the positional arguments for action. kwargs is a dictionary holding the keyword arguments for action.

    APScheduler的使用

    APScheduler的安装:pip install apscheduler。

    一、第一个APScheduler的使用案例

    每隔一秒打印出Hello World的字符。

    from apscheduler.schedulers.blocking import BlockingScheduler
    def my_job():
        print('Hello World')
    
    sched = BlockingScheduler()
    sched.add_job(my_job, 'interval', seconds=1)
    sched.start()

    友情链接

  • 相关阅读:
    React antd的select框的onchange事件 只能点击一次 如果想选中的值 还可以被点击 就用onselect事件
    formatTime.js
    typeScript
    React react-router在url参数不同的情况下跳转页面不更新
    React 组件
    三、猜字符小游戏
    二、Java学习之方法
    Java学习之数组
    JavaWeb的学习--第五天 javascript03
    JavaWeb的学习--第四天 javascript02
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusepythonapscheduler.html
Copyright © 2011-2022 走看看