【Python】模块学习之Timer定时任务,递归定时自调获取博客浏览量

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()建立了一个自调任务,实现了每十秒请求一次博客园获取浏览量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#! /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()
posted @   Bingo-he  阅读(2768)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航