0

I have the following python code in main which runs my program each 5 seconds

def main():
    while True:
        now = datetime.strptime((datetime.now().strftime("%H:%M")), "%H:%M")
        if datetime.strptime('23:59', "%H:%M") > now > datetime.strptime('07:30', "%H:%M"):
            start_time = time.time()
            while execute_data():
                time.sleep(5.0 - ((time.time() - start_time) % 5.0))

execute_data(): function once in 40 minutes does a job which takes a lot of time (nearly 3 min) when it finished its job my program goes crazy and runs once in every half second for example.

How can I solve this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • somewhere here `time.sleep(5.0 - ((time.time() - start_time) % 5.0))` – grumpyp Jan 21 '21 at 08:57
  • I'm not sure about the logic of your program. Why do you put a conditional? What happens when the function returns True? `break` makes the program exit from the loop. – fernand0 Jan 21 '21 at 09:01
  • @grumpyp still I want my program to run every 5 seconds except that long process which happened once in 40 min –  Jan 21 '21 at 09:09
  • @fernand0 If the function fails it returns Falls to re-run it, else it returns True and I finish the program –  Jan 21 '21 at 09:10
  • Your sleep code seems a little brittle. Have you tried the `schedule` library? It was designed for scheduling recurring tasks with Python: https://www.geeksforgeeks.org/python-schedule-library/ – tilman151 Jan 21 '21 at 09:26
  • @tilman151 thanks but I'm looking to solve this without using another package (my codes is currently using 10) and I don't want to make my program depend on so many external packages –  Jan 21 '21 at 09:59

0 Answers0