◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
在 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()
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。