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()

    友情链接

  • 相关阅读:
    Linux终端设置免密登陆ssh(以 XShell 为例)
    Docker入门(一)-安装
    find命令总结
    CentOS 恢复 rm -rf 误删除数据
    CentOS系统登陆root用户后发现提示符显示-bash-4.2#(已解决)
    一次在CentOS系统单用户模式下使用passwd命令破密失败的案例
    Ubuntu下配置IP地址
    安装CentOS 6.x报错"Disk sda contains BIOS RAID metadata"解决方法
    YUM命令总结
    git从安装到多账户操作一套搞定(二)多账户使用
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusepythonapscheduler.html
Copyright © 2011-2022 走看看