如何使用Python实现每分钟执行一次任务,而不影响其他任务的执行?

ID:20495 / 打印

如何使用python实现每分钟执行一次任务,而不影响其他任务的执行?

python 定时任务教程

问题:如何在 python 中实现间隔 1 分钟运行的任务,同时不影响其他任务的执行?

解答:

可以使用 python 的 threading模块和time模块来解决这个问题。以下是三种可行的解决方案:

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

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

import threading import time  class threading0(threading.thread):     def __init__(self):         threading.thread.__init__(self)     def run(self):         while true:   # 条件自定,不能为空。             time.sleep(60)   # 单位:秒  threading0().start() while true:   # 条件自定,不能为空。     # 执行不等待任务

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

import threading import time  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 threading import time  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()
上一篇: Python 中批量注释导致 while...else... 报语法错误的原因是什么?
下一篇: 使用随机基值改进快速排序:如何提升排序效率?

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

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

与本文相关文章

发表评论:

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