Hassan Abbas
Hassan Abbas

Reputation: 1316

How to run a thread in the background in python

class CORSRequestHandler (SimpleHTTPRequestHandler):

  def do_GET(self):
    thread1 = threading.Thread(target=test())
    thread1.daemon = True
    thread1.start()
    return SimpleHTTPRequestHandler.do_GET(self)

def test():
    while True:
        print "Hello"
        time.sleep(2)


if __name__ == '__main__':
    BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)

I need to run a server meanwhile printing Hello in the background. Can you please tell me what i am doing wrong because if a try to enter the url the page never loads up. However Hello is being printed and the server does start.

Upvotes: 0

Views: 2221

Answers (1)

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

You need to pass method test in target keyword argument of threading.Thread, not what test returns. So, replace

thread1 = threading.Thread(target=test())

with

thread1 = threading.Thread(target=test)

When you do target=test() test method is called right then, hence the infinite loop and the request never returns.

Upvotes: 3

Related Questions