Skip to content

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#

Python 3 (standard library)
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")
    raise

Node.js#

Node.js 18 or later
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#

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#

PowerShell (for example, from Windows Task Scheduler)
$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
}

Last updated