
python 定时任务教程
问题:如何在 python 中实现间隔 1 分钟运行的任务,同时不影响其他任务的执行?
解答:
可以使用 python 的 threading模块和time模块来解决这个问题。以下是三种可行的解决方案:
立即学习“Python免费学习笔记(深入)”;
方案一:有时间间隔代码放分线程
import threadingimport timeclass threading0(threading.thread): def __init__(self): threading.thread.__init__(self) def run(self): while true: # 条件自定,不能为空。 time.sleep(60) # 单位:秒threading0().start()while true: # 条件自定,不能为空。 # 执行不等待任务
方案二:无时间间隔代码放分线程
import threadingimport timeclass 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 threadingimport timeclass 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实现每分钟执行一次任务,而不影响其他任务的执行?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1351680.html
微信扫一扫
支付宝扫一扫