天天看點

Python: 定時運作程式

文章背景: 在日常工作中,有時我們需要

定時運作

某個程式。比如某個表格每天會随時更新,我們需要定時檢視,進而獲得最新的資料。下面介紹兩個方法實作定時運作程式。

1 while True: + sleep()實作定時任務

2 threading子產品中的Timer

1 while True: + sleep()實作定時任務

位于 time 子產品中的 sleep(secs) 函數,可以實作令目前執行的線程暫停 secs 秒後再繼續執行。所謂暫停,即令目前線程進入阻塞狀态,當達到 sleep() 函數規定的時間後,再由阻塞狀态轉為就緒狀态,等待 CPU 排程。

基于這樣的特性我們可以通過while死循環+sleep()的方式實作簡單的定時任務。

下面的代碼塊實作的功能是:每5秒列印一次時間。

from datetime import datetime
import time


# 每n秒執行一次
def timer(n):
    while True:
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        time.sleep(n)


# 主程式
timer(5)           

複制

注:The

strftime()

method returns a string representing date and time using date, time or datetime object.

上述代碼塊的運作效果:

Python: 定時運作程式

這個方法的缺點是,隻能執行

固定間隔時間

的任務,并且 sleep 是一個阻塞函數,也就是說在 sleep 這一段時間,目前程式無法執行其他任務。

2 threading子產品中的Timer

threading 子產品中的 Timer 是一個非阻塞函數,這一點比 sleep 稍好一些。缺點也是隻能執行

固定間隔時間

的任務。

Timer 函數第一個參數是時間間隔(機關是秒),第二個參數是要調用的函數名,第三個參數是調用函數的位置參數(可以使用元組或清單)。

threading.Timer

(interval, function, args=None, kwargs=None)

Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is

None

(the default) then an empty list will be used. If kwargs is

None

(the default) then an empty dict will be used.

下面的代碼塊實作的功能是:每5秒列印一次目前時間。

from datetime import datetime
from threading import Timer


# 列印時間函數
def print_time(inc):
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    t = Timer(inc, print_time, (inc,))
    t.start()


# 5s
print_time(5)           

複制

運作效果:

Python: 定時運作程式

上述代碼塊中運用了

遞歸

的思想。在

print_time

函數中,當列印出目前時間後,又設定了定時器線程Timer,這就完成了一個遞歸的操作,間隔5秒重複執行定時任務。

下面的代碼塊實作類似的功能:每5秒列印一次目前時間。

import time
import threading


def create_timer(inc):
    t = threading.Timer(inc, repeat, [inc])
    t.start()


def repeat(inc):
    print('Now:', time.strftime('%H:%M:%S', time.localtime()))
    create_timer(inc)


create_timer(5)           

複制

運作效果:

Python: 定時運作程式

參考資料:

[1] Python 實作定時任務的八種方案(https://cloud.tencent.com/developer/article/1887717)

[2] Python: 定時任務的實作方式(https://justcode.ikeepstudying.com/2019/10/python-%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F-crontab-%E4%BB%BB%E5%8A%A1-%E5%AE%9A%E6%97%B6%E8%BF%90%E8%A1%8C/)

[3] Python strftime() (https://www.programiz.com/python-programming/datetime/strftime)

[4] threading (https://docs.python.org/3/library/threading.html#timer-objects)

[5] python 線程定時器Timer (https://zhuanlan.zhihu.com/p/91412537)

[6] time (https://docs.python.org/3/library/time.html#module-time)