Python模組學習之Timer定時任務,函式自調實現定時獲取部落格園部落格瀏覽量
阿新 • • 發佈:2019-01-26
Timer定時任務
下面是Timer函式的官方doc介紹資訊
“””
Call a function after a specified number of seconds:
t = Timer(30.0, f, args=None, kwargs=None)
t.start()
t.cancel() # stop the timer’s action if it’s still waiting “”“
第一個引數時指定多長時間之後執行這個函式,第二個引數時呼叫的函式名,
後面兩個是可選函式,作為傳遞函式需要使用的引數,可以傳遞普通的引數和字典
t.start() 啟動這個定時任務,也可以使用t.cancel()在一定的條件來停止這個定時任務,
下面這行程式碼表示十秒鐘後呼叫一次views_count這個函式
Timer(10, views_count).start()
自調任務例項
下面的這個例項利用threading.Timer()建立了一個自調任務,實現了每十秒請求一次部落格園獲取瀏覽量
#! /usr/bin/python
# coding:utf-8
"""
@author:Administrator
@file:Timer_test.py
@time:2018/02/08
"""
import requests
import re
from threading import Timer
def views_count():
global count
global source_view
article_views = []
url = "http://www.cnblogs.com/Detector/default.html?page=%s"
for i in range(1, 5):
html = requests.get(url % i).text
article_view = re.findall("_Detector 閱讀\((.*?)\)", html)
article_views += article_view
count += 1
current_view = sum(map(lambda x: int(x), article_views))
if current_view - source_view > 50:
print("You have made great progress")
else:
print("current_view: ", current_view)
if count < 10000: # 執行一萬次
Timer(10, views_count).start()
count = 0
source_view = 2412 # 設定一個初始閱讀資料
Timer(10, views_count).start()