Use Go Context Deadlines for Cron Job Safety

Go

The Problem

A Go cron job that hangs indefinitely blocks the next scheduled run and wastes resources. Without a deadline, there's no automatic timeout.

The Solution

Use context.WithDeadline or context.WithTimeout to enforce maximum execution time, and pair it with CronRabbit for external monitoring.

Context Deadlines as a Safety Net

Go's context package lets you set a maximum runtime. If your job exceeds the deadline, downstream operations (HTTP calls, DB queries) are cancelled automatically.

Combining with CronRabbit

If your job is killed by a context deadline, send a /fail ping before exiting. CronRabbit then alerts you that the job timed out, so you can investigate.

Code Examples

Context deadline with monitoring

Go
package main

import (
	"context"
	"log"
	"net/http"
	"time"
)

func main() {
	client := &http.Client{Timeout: 10 * time.Second}
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
	defer cancel()

	client.Get("https://ping.cronrabbit.com/your-id/start")

	if err := runJobWithContext(ctx); err != nil {
		if ctx.Err() == context.DeadlineExceeded {
			log.Println("Job timed out")
		}
		client.Get("https://ping.cronrabbit.com/your-id/fail")
		log.Fatal(err)
	}

	client.Get("https://ping.cronrabbit.com/your-id")
}

Ready to Monitor Your Cron Jobs?

Create your free account and add your first monitor in under 5 minutes. No credit card required.