Python scripts that run every minute without stopping

I have a Python script that sends a mail request to my API every 1 minute:

while True:
    data = requests.post("URL_HERE", json={
        "api_key":"XXXX",
        "concat": 1,
        "messages": "HI"
    })
    time.sleep(60)

Everything works fine, but every 2 hours (more or less) there are 2 entries of the same minute. Example:

2017-03-22 11:34:46.977255
2017-03-22 11:37:47.231694
2017-03-22 11:37:47.231694
2017-03-22 11:39:48.849003
2017-03-22 11:40:48.907895
...
2017-03-23 13:59:59.150108
2017-03-23 14:00:00.120431
2017-03-23 14:00:00.942033

I suppose this is because the code inside the "while" takes a couple of milliseconds to execute, so it will have two entries every 2-3 hours per minute.

Does anyone know how I can fix this? I can not use cronjobs.

Could it be an asynchronous task?

And if I want this program to run forever, Okey use "while", or do I need to create Daemon o something like that?

+4
source share
3

60 :

time.sleep(60 - datetime.datetime.now().second)

, datetime.datetime.now().second 1 2, 59 58 .

+4

. . .

import sched, time, requests
schedul = sched.scheduler(time.time, time.sleep)

def send_post():
    data = requests.post("URL_HERE", json={
        "api_key": "XXXX",
        "concat": 1,
        "messages": "HI"
    })

schedul.enter(60, 1, send_post(), (schedul,))
schedul.run()  
+2

, , .

interval = 60
next = time.time() + interval

while True:
    if time.time() >= next :
        data = requests.post("URL_HERE", json={
            "api_key":"XXXX",
            "concat": 1,
            "messages": "HI"
        })
        next = next + interval
    time.sleep(next - time.time())
+1

Source: https://habr.com/ru/post/1673014/


All Articles