Graceful Shutdown for Go Cron Jobs with Monitoring
GoThe Problem
When a Go cron job receives SIGTERM (from Docker, systemd, or Kubernetes), it may exit before completing. Without signal handling, partial work and missing pings cause confusion.
The Solution
Trap OS signals with os/signal, perform cleanup, and send a /fail ping to CronRabbit so you know the job was interrupted.
Signal Handling Pattern
Use signal.NotifyContext to create a context that cancels on SIGTERM/SIGINT. Pass this context through your job logic for clean cancellation.
Reporting Interrupted Jobs
If the context is cancelled by a signal, send /fail to CronRabbit before exiting. This distinguishes between crashes and graceful interruptions in your alert history.
Code Examples
Signal-aware cron job
Gopackage main
import (
"context"
"log"
"net/http"
"os/signal"
"syscall"
"time"
)
func main() {
client := &http.Client{Timeout: 10 * time.Second}
ctx, stop := signal.NotifyContext(
context.Background(), syscall.SIGTERM, syscall.SIGINT,
)
defer stop()
client.Get("https://ping.cronrabbit.com/your-id/start")
if err := runJob(ctx); err != nil {
if ctx.Err() != nil {
log.Println("Interrupted by signal")
}
client.Get("https://ping.cronrabbit.com/your-id/fail")
log.Fatal(err)
}
client.Get("https://ping.cronrabbit.com/your-id")
}