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