Skip to content

5.7Kubernetes CronJob

A Kubernetes CronJob runs a container on a schedule. Wrap the job's command in a short shell script: ping /start, run the job, then send its exit code. Keep the ping URL in a Kubernetes Secret.

Create the secret
kubectl create secret generic obsrvly-heartbeat \
  --from-literal=url='https://<your-ping-url>'
cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
spec:
  schedule: "15 2 * * *"
  timeZone: "Europe/Berlin"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      backoffLimit: 0
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: report
              image: registry.example.com/report:1.4.2
              env:
                - name: PING_URL
                  valueFrom:
                    secretKeyRef:
                      name: obsrvly-heartbeat
                      key: url
              command: ["/bin/sh", "-c"]
              args:
                - |
                  curl -fsS -m 10 --retry 3 "$PING_URL/start" > /dev/null || true
                  /app/run-report
                  status=$?
                  curl -fsS -m 10 --retry 3 "$PING_URL/$status" > /dev/null || true
                  exit $status
  • Use the same cron expression and timezone in the monitor as in schedule and timeZone. Without timeZone, Kubernetes uses its own zone, so set the monitor to match.
  • The container image needs sh and curl. If it has neither, send the pings from your code (5.9).
  • || true keeps a failed ping from failing the job. exit $status keeps the job's own result.
  • With backoffLimit: 0, Kubernetes does not retry a failed run. If you allow retries, each retry reports its own result.

Last updated