-3

my code sometimes work in 17 sec sometimes 23 sec sometimes 40 seconds it changes with my connection speed and with datas that i get. but i want to repeat working in every next 5 min like 12:05 12:10 12:15. but because of working time it changes like 12:05 12:11 12:16. my code is running all day because of time difference at the end of the day i get nearly 30 minute loos. if you help me i ll be glad have a nice day for all

import time
from datetime import datetime
def main():
present_time=datetime.now()

 *****MY CODE HERE*****
print(datetime.strftime(present_time,"%X"))
while True:
     main()
     time.sleep(300)
Alper Aşan
  • 65
  • 1
  • 7

1 Answers1

1

It seems you want something like the following, which will cause the program to sleep up till the next 5 minute mark at most. If the run time of your code exceeds 5 minutes, it will not sleep, and instead start the next 5 minute interval immediately.

from time import time, sleep

def main():
    # *****YOUR CODE HERE*****

while True:
    start_time = time()
    main()
    sleep(max(0, 5 * 60 + start_time - time()))
Dillon Davis
  • 6,679
  • 2
  • 15
  • 37
  • it doesnt work exactly that i want mate – Alper Aşan Feb 22 '19 at 08:45
  • 2
    @AlperAşan I don't understand. Your post seems to suggest you want it to start / stop at exact 5-minute schedules, and this is what my code does. – Dillon Davis Feb 22 '19 at 08:49
  • i want it to work every 5 minutes with in code working time. my problem is code is working at different times. sometime 17 sec or 20 sec or 40 sec. when i type this code it works 5:17 minutes or 5:20 minutes. did i explain my problem mate? – Alper Aşan Feb 22 '19 at 08:53
  • 2
    @AlperAşan my code accounts for that. If your code takes 4min 50sec, the above code will sleep for 10 seconds, for a total run time 5 minutes. You can try it by substituting `5 * 60` for some smaller, easier to measure time frame if you don't believe me. – Dillon Davis Feb 22 '19 at 08:55
  • 2
    @AlperAşan Have you removed the `sleep(300)` from your original code? – Thierry Lathuille Feb 22 '19 at 08:58
  • @AlperAşan once you've run this code and seen it does in fact work, please consider retracting your downvote, unless there are further issues. – Dillon Davis Feb 22 '19 at 09:13
  • @DillonDavis The OP can't be the downvoter, as he doesn't have the necessary (125) reputation to do that. – Thierry Lathuille Feb 22 '19 at 09:26
  • @ThierryLathuille ah, you're right. By the tone of his comments it sounded like he was replying as the downvoter. – Dillon Davis Feb 22 '19 at 09:28
  • @DillonDavis maybe you are getting angry to me but i typed your code and first data time is 20:36:28 and second data time is 20:42:11. i wanna mean that i want second data time at 20:41:28 thats all. – Alper Aşan Feb 23 '19 at 17:57