安装依赖
pip install stopit
实现代码
task 任务运行 10 秒钟后停止
import time
import traceback
import stopit
def task(name):
print('Start')
for i in range(1, 100):
print("%d seconds have passed %s" % (i, name))
time.sleep(1)
@stopit.threading_timeoutable()
def worker(name):
try:
task(name)
except stopit.utils.TimeoutException:
print('timeout!!!')
def main():
worker('yuziyue', timeout=10)
if __name__ == '__main__':
main()