Skip to content

Instantly share code, notes, and snippets.

@arya2004
Created January 24, 2025 17:52
Show Gist options
  • Select an option

  • Save arya2004/4866ec191b3d1d09d426506a32c5097c to your computer and use it in GitHub Desktop.

Select an option

Save arya2004/4866ec191b3d1d09d426506a32c5097c to your computer and use it in GitHub Desktop.
This Gist provides examples of how to create and schedule cron jobs for monitoring purposes. It includes a Bash script and a Go application that both check the availability of `google.com` every 5 minutes.

Cron Job Examples: Bash and Golang

This repository contains two examples of how to monitor google.com every 5 minutes using a Bash script and a Go application.


1. Bash Script Execution Instructions

Create and Set Up the Script

  1. Save the Bash script from check_google.sh in this repository.
  2. Make it executable:
    chmod +x check_google.sh

Set Up a Cron Job

  1. Open the crontab file:
    crontab -e
  2. Add the following line to run the script every 5 minutes:
    */5 * * * * /path/to/check_google.sh >> /path/to/check_google.log 2>&1

Logs

The output of the script will be saved in check_google.log.


2. Golang Application Execution Instructions

Run the Go Application

Option 1: Run directly:

go run main.go >> go-cron-check.log 2>&1 &

Option 2: Build and execute the binary:

go build -o go-cron-check
./go-cron-check >> go-cron-check.log 2>&1 &

Logs

The output of the Go application will be saved in go-cron-check.log.

#!/bin/bash
if ping -c 1 google.com &> /dev/null
then
echo "$(date): google.com is reachable."
else
echo "$(date): google.com is not reachable."
fi
package main
import (
"fmt"
"net/http"
"time"
"github.com/robfig/cron/v3"
)
func main() {
c := cron.New()
// Schedule a job to run every 5 minutes
c.AddFunc("*/5 * * * *", func() {
checkGoogle()
})
// Start the cron scheduler
c.Start()
// Keep the main goroutine alive
select {}
}
func checkGoogle() {
client := &http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Get("https://www.google.com")
if err != nil {
fmt.Println(time.Now().Format(time.RFC3339), ": google.com is not reachable. Error:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
fmt.Println(time.Now().Format(time.RFC3339), ": google.com is reachable.")
} else {
fmt.Println(time.Now().Format(time.RFC3339), ": google.com returned status:", resp.StatusCode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment