Python 在 n 秒后停止一个线程 [英] Python stop a thread after n seconds

查看:51
本文介绍了Python 在 n 秒后停止一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 5 秒后停止线程?我想每秒钟打印一次Hello World",然后在 5 秒后停止.这是我的代码:

How can i stop a thread after 5 seconds? I want to print "Hello World" every seconds and then stop after 5 seconds. This is my code:

import threading

def printthis():
   threading.Timer(1.0, printthis).start()
   print("Hello, World!")

printthis()

推荐答案

这个怎么样:

def printthis():
    print_count = 0
    while print_count < 5: # 5 because print_count will be 5 after printing the 5th time
        threading.Timer(1.0, printthis).start()
        print("Hello, World!")
        print_count += 1 
printthis()

这篇关于Python 在 n 秒后停止一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆