Python 线程定时器Timer
2023-09-14 08:56:57 时间
一.线程定时器Timer原理
原理比较简单,指定时间间隔后启动线程,适用场景:完成定时任务,例如:定时提醒-闹钟等等.
# 导入线程模块 import threading timer = threading.Timer(interval, function, args=None, kwargs=None)
参数介绍:
interval — 定时器间隔,间隔多少秒之后启动定时器任务(单位:秒);
function — 线程函数;
args — 线程参数,可以传递元组类型数据,默认为空(缺省参数);
kwargs — 线程参数,可以传递字典类型数据,默认为空(缺省参数);
二、测试代码
from datetime import datetime from threading import Timer import time ''' 每个 10 秒打印当前时间。 ''' def timedTask(): ''' 第一个参数: 延迟多长时间执行任务(单位: 秒) 第二个参数: 要执行的任务, 即函数 第三个参数: 调用函数的参数(tuple) ''' Timer(10, task, ()).start() # 定时任务 def task(): print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) if __name__ == '__main__': timedTask() while True: print(time.time()) time.sleep(5)
运行结果:
1512486945.1196375
1512486950.119873
2017-12-05 23:15:50
1512486955.133385
三、Timer定时器每3秒执行任务
from threading import Timer import psutil import datetime def MonitorSystem(logfile = None): cpuper = psutil.cpu_percent() mem = psutil.virtual_memory() memper = mem.percent now = datetime.datetime.now() ts = now.strftime('%Y-%m-%d %H:%M:%S') line = f'{ts} cpu:{cpuper}%, mem:{memper}%' print(line) if logfile: logfile.write(line) #启动定时器任务,每三秒执行一次 Timer(3, MonitorSystem).start() MonitorSystem()
更多定时任务的实现方式:https://blog.51cto.com/huangyg/2367088
相关文章
- python代码补全工具Kite
- python中实现mysql连接池
- Python - Pycharm的使用方法和技巧
- 【python cookbook】【字符串与文本】11.从字符串中去掉不需要的字符
- Python 字符串_python 字符串截取_python 字符串替换_python 字符串连接
- python插入记录后获取最后一条数据的id
- Python 刷Leetcode题库,顺带学英语单词(9)
- [Py] Jupyter 写入和执行 python 文件
- Atitit nlp自然语言处理类库(java python nodejs c#net) 目录 1.1. Python snownlp1 1.2. NLP.js一个nodejs/javascri
- Python语言学习:利用python获取当前/上级/上上级目录路径(获取路径下的最后叶目录的文件名、合并两个不同路径下图片文件名等目录/路径案例、正确加载图片路径)之详细攻略
- 〖Python 数据库开发实战 - MySQL篇㉘〗- MySQL 日期函数
- Python从入门到爬虫案例实现~
- 超全整理:机器学习和 Python 技术路线来了
- Python学习65:进程 vs. 线程
- 【华为OD机试Python实现】HJ17 坐标移动 (中等)
- Python编程:查看python环境支持的whl
- Python编程:pyenv管理多个python版本环境
- Python使用事件信号进行线程同步
- python调用window dll和linux so例子
- 多版本Python共存时pip给指定版本的python安装package的方法
- python的open打开图片通过企业微信接口发送
- Python: 爬虫入门-python爬虫入门教程(非常详细)
- 【异常】前端ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
- Python可视化数据分析01、python环境搭建
- Python使用技巧(十五):静态类方法@staticmethod和@classmethod
- Airtest自动化测试篇——python编写和执行用例(下)