如何用 Python 实现间隔执行任务而不影响其他任务?

ID:20533 / 打印

如何用 python 实现间隔执行任务而不影响其他任务?

python 间隔执行任务而不影响其它任务

python 中计时并让任务以间隔时间运行,又不影响其它任务,可以通过多线程实现。以下是如何用 threading 和 time 模块来完成:

方案一:有时间间隔代码放到线程

将有时间间隔的任务放到单独线程中执行,从而不影响主线程。代码如下:

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

import time import threading  class threading0(threading.thread):     def __init__(self):         threading.thread.__init__(self)      def run(self):         while true:   # 条件自定,不能为空。             # 执行等待任务(时间不超过1秒,超过1秒可从sleep中减去)。             time.sleep(60)   # 单位:秒  threading0().start()  while true:   # 条件自定,不能为空。     # 执行不等待任务

方案二:无时间间隔代码放到线程

与方案一类似,将无时间间隔的任务放到单独线程中执行。代码如下:

import time import threading  class threading0(threading.thread):     def __init__(self):         threading.thread.__init__(self)      def run(self):         while true:   # 条件自定,不能为空。             # 执行不等待任务  threading0().start()  while true:   # 条件自定,不能为空。     # 执行等待任务(时间不超过1秒,超过1秒可从sleep中减去)。     time.sleep(60)   # 单位:秒

方案三:有时间间隔代码和无时间间隔代码统统放到线程

如果既有时间间隔的任务,又有无时间间隔的任务,可以将它们都放到各自的线程中执行。代码如下:

import time import threading  class threading0(threading.Thread):     def __init__(self):         threading.Thread.__init__(self)      def run(self):         while True:   # 条件自定,不能为空。             # 执行不等待任务  class threading1(threading.Thread):     def __init__(self):         threading.Thread._init__(self)      def run(self):         while True:   # 条件自定,不能为空。             # 执行等待任务(时间不超过1秒,超过1秒可从sleep中减去)。             time.sleep(60)   # 单位:秒  t0 = threading0() t1 = threading1() t0.start() t1.start()  # 下面的代码可要可不要,只是用于等待线程运行完毕,如果是死循环,那么就可以不写下面的代码。 t1.join() t2.join()  # 执行线程结束后需要运行的代码。(不用运行代码的就当我没说)
上一篇: Python Join 方法报错,如何解决?
下一篇: 如何去除打印字典时出现的不必要的空行?

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

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

与本文相关文章

发表评论:

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