简体   繁体   English

Python在n秒后停止线程

[英]Python stop a thread after n seconds

How can i stop a thread after 5 seconds? 5秒后如何停止线程? I want to print "Hello World" every seconds and then stop after 5 seconds. 我想每秒钟打印一次“ Hello World”,然后在5秒钟后停止。 This is my code: 这是我的代码:

import threading

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

printthis()

How about this: 这个怎么样:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM