How to Monitor Background Job Health in Go

Monitor background job health in Go by exposing a metrics endpoint that reports job status, error counts, and last execution time via `runtime/metrics` or custom counters. Use a goroutine to track job state and expose it through an HTTP handler for external monitoring tools.

How to Monitor Background Job Health in Go

Monitor background job health in Go by exposing a metrics endpoint that reports job status, error counts, and last execution time via runtime/metrics or custom counters. Use a goroutine to track job state and expose it through an HTTP handler for external monitoring tools.

package main

import (
	"fmt"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

var (
	jobRunning    atomic.Bool
	jobErrorCount atomic.Int64
	lastRunTime   atomic.Int64
)

func startJob() {
	for {
		jobRunning.Store(true)
		lastRunTime.Store(time.Now().Unix())
		// Simulate job work
		time.Sleep(5 * time.Second)
		jobRunning.Store(false)
		// Simulate occasional error
		if time.Now().Unix()%10 == 0 {
			jobErrorCount.Add(1)
		}
	}
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Running: " + strconv.FormatBool(jobRunning.Load()) + "\n"))
	w.Write([]byte("Errors: " + strconv.FormatInt(jobErrorCount.Load(), 10) + "\n"))
	w.Write([]byte("Last Run: " + time.Unix(lastRunTime.Load(), 0).Format(time.RFC3339) + "\n"))
}

func main() {
	go startJob()
	http.HandleFunc("/health", healthHandler)
	fmt.Println("Server starting on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Printf("Server failed: %v\n", err)
	}
}