0

I'm trying to repeat an event every so often (doesn't matter how long, say 60 seconds) in python but I'm having some trouble. This is what I have and it should work (I thought) but it isn't:

def timedMessages():

    time_elapsed = time.time() - start_time

    if time_elapsed > 60:
        sendMessage("test")
        start_time = time.time()
        time_elapsed = 0
    else:
        time_elapsed = time.time() - start_time

start_time = time.time()

The timedMessages() function is called inside a while loop else where and start_time is set at time.time() when the program is launched. The problem occurs because my local start_time is set as a local variable again inside the timeMessages function. I'm not sure if I'm doing it wrong logically or I'm just missing something small.

Droid
  • 65
  • 1
  • 9
  • 1
    can't you use `time.sleep(60)` ? – Omar Einea Jan 05 '18 at 19:52
  • you could just in-line this code in the while loop that way you’re not messing yourself up with closing over variables in different scopes.. if i wasn’t on my phone i would code up something for you, perhaps using a generator. or use the `sleep` method as the other guy suggested. – mad.meesh Jan 05 '18 at 19:58
  • Possible duplicate of [What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python) – wwii Jan 05 '18 at 20:55
  • Also .. [Schedule a repeating event in Python 3](https://stackoverflow.com/q/2398661/2823755) – wwii Jan 05 '18 at 20:58
  • I can't use time.sleep() because there are other actions that need to run at the same time – Droid Jan 05 '18 at 22:39

1 Answers1

0

The most basic solution would be something like

while True:
    send_message()
    time.sleep(60)

If send_message() takes a while and you want more accurate timing, you could do something like

while True:
    start_time = time.time()
    send_message()
    elapsed_time = time.time() - start_time

    time.sleep(60 - elapsed_time)

That version tries to actually run it every 60 seconds by subtracting the execution time of send_message() from the sleep, so that it starts executing every 60 seconds.

If you want very accurate timing, you're going to need a more advanced technique.

Josh Karpel
  • 2,110
  • 2
  • 10
  • 21