Python线程实现超时自动退出

26 篇文章 6 订阅

我们跑代码往往有一个需求,如果代码出错不希望它hang那边或者代码出错一直运行占用系统资源。最近跑Spark SQL发现有的Application总会因为配置参数出错而hang那边半天,就很烦。搜了一下代码,发现好多人写的又垃圾又难用,这里贴上我的可用的代码模板:

# coding=utf-8
import threading

#运行你的应用程序的函数,自定义实现
def runApp():
    for i in range(10000000):
        print(i)
        
#杀死你应用程序的函数,自定义实现
def killApp():
    exit()

if __name__ == '__main__':
    # 设置超时时间为1s
    timeLimit = 1
    t = threading.Thread(target=runApp)
    t.setDaemon(True)
    #运行你的应用程序
    t.start()
    t.join(timeLimit)
    print("it's over")
    #如果线程还在运行,就杀死它
    killApp()

唯一你需要关注的参数就是timiLimit,它表示你希望你的应用运行多长时间退出,一般最后需要加入杀死应用程序的代码,在runAPP以及killAPP里自定义你的代码即可,亲测可用!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中停止线程的方法有以下几种: 1. 使用标志位:在线程中使用一个标志位,当标志位为 True 时线程继续运行,当标志位为 False 时线退出。 ```python import threading class MyThread(threading.Thread): def __init__(self): super().__init__() self._stop_event = threading.Event() def stop(self): self._stop_event.set() def run(self): while not self._stop_event.is_set(): # 线程运行的代码 my_thread = MyThread() my_thread.start() # 停止线程 my_thread.stop() ``` 2. 使用Thread类的stop方法(不推荐):调用Thread类的stop方法可以直接停止线程,但是这种方法不推荐使用,因为它可能会导致线程的数据损坏。 ```python import threading class MyThread(threading.Thread): def run(self): while True: # 线程运行的代码 my_thread = MyThread() my_thread.start() # 停止线程 my_thread.stop() ``` 3. 使用Thread类的join方法:调用Thread类的join方法可以阻塞主线程,直到子线退出。可以设置一个超时时间,如果超时时间到达子线程还没有退出,那么可以判断子线程可能出现了问题,需要进行处理。 ```python import threading class MyThread(threading.Thread): def run(self): while True: # 线程运行的代码 my_thread = MyThread() my_thread.start() # 停止线程 my_thread.join(timeout=1) ``` 注意:以上方法中,使用标志位是最常用的方法。如果需要停止线程,建议优先考虑使用标志位的方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值