Python 中如何实现计时并间隔执行任务,又不影响其他任务?

ID:20479 / 打印

python 中如何实现计时并间隔执行任务,又不影响其他任务?

在 python 中计时并间隔执行任务

如何定时运行任务并在 python 中不影响其他任务?这个问题可以通过使用多线程和时间模块来解决。

方案一:将时间间隔代码放在单独的线程中

import threading import time  class timerthread(threading.thread):     def run(self):         while true:               # 执行等待任务(时间不超过1秒)             time.sleep(60)  # 开启定时线程 timer = timerthread() timer.start()  # 主线程执行不等待任务 while true:     pass 

方案二:将所有代码放在单独的线程中

立即学习“Python免费学习笔记(深入)”;

import threading import time  class workerthread(threading.thread):     def run(self):         while true:               # 执行不等待任务             pass          while true:               # 执行等待任务(时间不超过1秒)             time.sleep(60)  # 开启工作线程 worker = workerthread() worker.start() 

方案三:按需创建线程

import threading import time  # 主线程执行不等待任务 while True:     # 检查是否需要运行等待任务     # 创建并启动定时线程     timer = TimerThread()     timer.start()     timer.join() 
上一篇: Python 中如何通过函数命名空间定义变量?
下一篇: 在安装 Python 时遇到“gcc: error: directory: No such file or directory”错误怎么办?

作者:admin @ 24资源网   2025-01-14

本站所有软件、源码、文章均有网友提供,如有侵权联系308410122@qq.com

与本文相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。