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

    友情链接

  • 相关阅读:
    http
    VUE-1
    AJAX
    html常用标签
    CSS网页布局
    概念整理3
    SEO
    概念整理2
    var
    概念整理
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusepythonapscheduler.html
Copyright © 2020-2023  润新知