So you running public website and you have something like Jenkins server where you can execute small programs and monitor state of your website. There are many advanced paid solutions for that, but in this tutorial we going to try build simple app in Python.

First thing first we need to layout requirements:

  • Make a request to specified URL
  • Get response and check status code
  • It would be nice to measure response time
  • We will need to run the requests on schedule (every 15 seconds)
  • Get alert if something goes wrong

Ok we got our requirements lets see the solution:

# health_check.py
import requests
import schedule
import time


def fetch_url():
    response = requests.get('http://93days.me')
    status_code = response.status_code
    response_time = response.elapsed.total_seconds()
    if status_code == 200 and response_time < 3:
        print(f'The status code: {status_code}, Response time: {response_time}')
    else:
        print(f'We are in trouble Huston')


schedule.every(15).seconds.do(fetch_url)

while True:
   schedule.run_pending()
   time.sleep(1)

Now all is left is start the program, open up the terminal navigate to your file directory and run:

python health_check.py

Here is what happening when we run the program, first we import 3 libraries (requests, schedule, time). In fetch_url() function we making request to the url, retrieving status code and response time(I’m using response elapsed here). Then we have if else condition where we check the status code with response time and printing the message based on results. Now since we got our function we need to tell the program how often we want to make a call, in my case every 15 seconds. And the whole thing going to run with while loops, while conditions is True.

As you can see it is a small demo project, but you can go creative and add slack notifications or email alerts. We could also store response time in database and then produce some nice graphs with d3.js or similar libraries. I hope you got the idea and as always feel free post your comments, suggestions in the section below.