0

I would like to use Timer to exit a script where an infinite loop is running.
Here is a simple stub that I created to test that logic:

import threading
import sys 
import time


def exit():
    sys.exit()

if __name__ == '__main__':
    t = threading.Timer(3, exit)
    t.start()
    while True:
        time.sleep(3)

This doesn't make the script to sys.exit though. Any pointer why, and how can i achieve the Timer to sys.exit the main thread?

jim jarnac
  • 4,804
  • 11
  • 51
  • 88
  • Can you put the loop in the thread you spawn in the main? Then you can use [this answer](https://stackoverflow.com/a/36499538/5124383) – Finn Jun 16 '20 at 10:57
  • @Finn Maybe but i find it quite convoluted and hard to read.. I'm new to threading though maybe i just need to get more into it. However in the meantime I would be keen on understanding why my example doesn't work. – jim jarnac Jun 16 '20 at 11:05
  • 1
    Surely you need to start the timer by calling `start()`? – Joshua Nixon Jun 16 '20 at 11:22
  • @JoshuaNixon, want to post that as the answer? – Daniel Walker Jun 16 '20 at 11:42
  • @JoshuaNixon Thx i fixed that and another typo that was in the code - however it is still not working.. (still doesnt exit) – jim jarnac Jun 16 '20 at 11:51
  • Does this answer your question? [Why does sys.exit() not exit when called inside a thread in Python?](https://stackoverflow.com/questions/905189/why-does-sys-exit-not-exit-when-called-inside-a-thread-in-python) – Daniel Walker Jun 16 '20 at 11:59
  • 1
    yep actually this had the perfect answer - super lean. https://stackoverflow.com/questions/39297166/is-it-possible-to-kill-the-parent-thread-from-within-a-child-thread-in-python – jim jarnac Jun 16 '20 at 12:02

0 Answers0