3

I am developing a software with python. And I want my code to run at certain hours. It will run once every 5 minutes without a break. But I want it to work exactly at certain hours and minutes. For example, such as 20:00, 20:05, 20:10...

I used time.sleep(300) but if for example 5 seconds passes after my program runs, it starts to delay 5 seconds in each run and for example it starts running 1 minute late after 12 runs. For example, it should work at 20:05, but it starts at 20:06.

How can I provide this?

yunusus
  • 81
  • 5
  • 1
    Assuming the program isn't doing anything but sleeping in between runs the easiest way would probably be to use a CRON job to run the program at the specified times rather than sleeping the program. – paul41 Aug 08 '21 at 13:00
  • cron is proper way you should consider. – Shuduo Aug 08 '21 at 13:03

4 Answers4

2

You can use schedule module

import schedule
import time
from datetime import datetime

now = datetime.now()

def omghi():
    print("omg hi there xD")


schedule.every(5).minutes.do(omghi)


while True:
    schedule.run_pending()
    time.sleep(1)
Blue Duck
  • 56
  • 7
0

There is a useful model for that case. It is an external model, you have to download it using pip and it is called schedule https://pypi.org/project/schedule/ - here you can see all the details.

Eladtopaz
  • 1,036
  • 1
  • 6
  • 21
0

I believe that using timed threads works the best with what you want. This excellent answer uses threading.Timer from the library threading as follows:

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()
zaibaq
  • 120
  • 6
0

Thank you very much for the answers. But this is how I handled it and I wanted to share it with you :)

import time
from datetime import datetime

while True:
    now = datetime.now()

    if (now.minute % 5) == 0 and now.second == 0:
        print("Fire!")

    time.sleep(1)
yunusus
  • 81
  • 5