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

 

友情鏈接

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM