Published on

Python with Heartbeat

Authors
python-heartbeat.

Why do you need a Heartbeat with realtime processing job?

when you write the python code with a real-time processing, to ensure that your code is running well. You need to have some service to check whether your python healthy by call to some service consistently. We call this technique is "Heartbeat". Moreover, you do not need to create your own heartbeat service because there are many free service such as https://betterstack.com/better-uptime

How to use Heartbeat for real-time processing

While you run your code, it should have another process that use GET or POST method parallel with your real-time processing. How you create 2 parallel task? You just use schedule to create another parallel process that call every DURATION seconds at your endpoint HEARTBEAT_URL

installation

pip install schedule

Source Code

https://github.com/wuttichai-hung/getting-started-with-flask

Let's code it

heartbeat.py
import requests
import schedule

DURATION = 60
HEARTBEAT_URL = 'https://endpoint.com'
s = requests.Session()

def _send_heartbeat(HEARTBEAT_URL):
    r = s.get(HEARTBEAT_URL)
    print(f'Hit heart beat with status code:{r.status_code}')

schedule.every(DURATION).seconds.do(_send_heartbeat, HEARTBEAT_URL) # call _send_heartbear every 60 seconds at https://endpoint.com
try:
    while True:
        schedule.run_pending()
        """ Your Code
        """
except Exception as e:
    schedule.clear() # clear all of scheduler task
    raise Exception(e)