本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

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

网络教程 app 1℃

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

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

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

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

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

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

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

方案三:按需创建线程

import threadingimport time# 主线程执行不等待任务while True: # 检查是否需要运行等待任务 # 创建并启动定时线程 timer = TimerThread() timer.start() timer.join()

以上就是Python 中如何实现计时并间隔执行任务,又不影响其他任务?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » Python中如何实现计时并间隔执行任务_又不影响其他任务?

喜欢 (0)