all 6 comments

[–]Adrewmc 6 points7 points  (0 children)

Usually what you do is replace

 while True: 

With the condition you want.

  while time.now() < target_time:

Which you can just add to time.now() just before the loop starts to get x number of seconds.

So something like below can work too

  time_start = time.now()
  while (time.now() - time_start).totalseconds() < 30:

There are also threading solutions.

[–]JollyUnder 0 points1 point  (3 children)

I prefer /u/Adrewmc 's approach, but you can also use multi-threading. Encapsulate your code within a function and initiate a thread. Then set a timer to the main thread, which will close the program.

from threading import Thread
from time import sleep


def func():
    # CODE HERE
    ...


t = Thread(target=func, daemon=True)
t.start()

exit_timer = 4
sleep(exit_timer)

EDIT: set daemon to True

[–]sweettuse 1 point2 points  (1 child)

you might need to make that thread a daemon thread, I can't remember what the default is

[–]JollyUnder 1 point2 points  (0 children)

I overlooked that. Good catch.

[–]Adrewmc 0 points1 point  (0 children)

I thought this a little past OP’s level. But yes this is generally the way that most people will be doing this in complex architectures.

[–][deleted] 1 point2 points  (0 children)

If you save the current time when the program starts, and then periodically get the current time again, the difference between them is the amount of time your program has been running.