5.9From code
Send pings from your program when you cannot wrap the job in a shell script. There is no obsrvly library to install. A plain HTTP request is enough.
- Read the ping URL from an environment variable, here
PING_URL. Do not write it into your code. - Set a short timeout, such as 10 seconds.
- Ignore ping errors. A ping problem must never break the job.
In each example, replace run_job, runJob or the script path with your own job.
Python#
import os
import urllib.request
PING_URL = os.environ["PING_URL"]
def ping(suffix=""):
try:
req = urllib.request.Request(PING_URL + suffix, method="POST")
urllib.request.urlopen(req, timeout=10)
except Exception:
pass # a failed ping must never fail the job
ping("/start")
try:
run_job()
ping()
except Exception:
ping("/fail")
raiseNode.js#
const PING_URL = process.env.PING_URL;
async function ping(suffix = "") {
try {
await fetch(PING_URL + suffix, {
method: "POST",
signal: AbortSignal.timeout(10_000),
});
} catch {
// a failed ping must never fail the job
}
}
async function main() {
await ping("/start");
try {
await runJob();
await ping();
} catch (err) {
await ping("/fail");
throw err;
}
}
main();Go#
package main
import (
"net/http"
"os"
"time"
)
var (
pingURL = os.Getenv("PING_URL")
client = &http.Client{Timeout: 10 * time.Second}
)
// A failed ping must never fail the job, so errors are ignored.
func ping(suffix string) {
resp, err := client.Post(pingURL+suffix, "text/plain", nil)
if err == nil {
resp.Body.Close()
}
}
func main() {
ping("/start")
if err := runJob(); err != nil {
ping("/fail")
os.Exit(1)
}
ping("")
}PowerShell#
$PingUrl = $env:PING_URL
function Send-Ping([string]$Suffix = "") {
try {
Invoke-RestMethod -Method Post -Uri ($PingUrl + $Suffix) `
-TimeoutSec 10 | Out-Null
}
catch { } # a failed ping must never fail the job
}
Send-Ping "/start"
try {
& C:\Jobs\nightly-export.ps1
if ($LASTEXITCODE -and $LASTEXITCODE -ne 0) {
throw "exit code $LASTEXITCODE"
}
Send-Ping
}
catch {
Send-Ping "/fail"
throw
}