Ping CronMissed from Python
On this page
Python needs no extra package to ping: urllib is enough. This decorator wraps any job function so it reports its start, its success, and its failure with the end of the traceback, and a failed ping is swallowed.
What should a Python job send?
- A request to
/startbefore the work, so CronMissed can time the run and notice a job that never finishes. - A request to the plain URL when the work succeeded, or to
/failwhen it did not./<exit status>works too: 0 is a success and any other number is a failure. - The end of the output in the request body, up to 100,000 bytes, so the alert shows the error without a trip to the server.
What is the decorator?
monitored.py
import functools
import os
import traceback
import urllib.request
PING_URL = os.environ["CRONMISSED_PING_URL"]
def ping(suffix="", body=None):
request = urllib.request.Request(PING_URL + suffix, data=body, method="POST" if body else "GET")
try:
urllib.request.urlopen(request, timeout=10).read()
except OSError:
pass # a lost ping must never break the job
def monitored(job):
@functools.wraps(job)
def wrapper(*args, **kwargs):
ping("/start")
try:
result = job(*args, **kwargs)
except Exception:
ping("/fail", traceback.format_exc().encode()[-100000:])
raise
ping()
return result
return wrapper
@monitored
def nightly_export():
...Keep the ping URL in an environment variable or a secret store, never in a public repository: the URL is the check's only credential.
Where else does Python run on a schedule?
For Celery beat, connect the task signals; for APScheduler, add a job listener; for Airflow, add a final task. The ping function above works in all of them.
Questions and answers
- If it is already a dependency, yes: requests.post(url, data=body, timeout=10) is shorter. The standard library version avoids adding one just for a ping.
- Wrap the coroutine the same way, awaiting it inside the try block. Keep the ping itself synchronous with a short timeout, or run it in a thread, so it cannot block the loop for long.
Should I use requests instead of urllib?
What if the job is async?
Create the check these snippets report to
Make a check, copy its ping URL into the snippet, and run the job once.
Start monitoring