Run a Cron Job Only If Network Is Up

Sometimes you want a scheduled task to run only when you’re online — for example, syncing backups, pulling data from an API, or uploading…

Run a Cron Job Only If Network Is Up
Photo by Mika Baumeister on Unsplash

Sometimes you want a scheduled task to run only when you’re online — for example, syncing backups, pulling data from an API, or uploading logs. But “internet up” doesn’t always mean access to public internet; it might also mean access to a local network or private IP.

Let’s walk through how to conditionally run a cron job only when network connectivity is confirmed, using ping.

✅ Why Use ping?

The ping command is a lightweight way to check if a host is reachable. By combining it with cron, we can decide whether to proceed with a job.

🔧 Example 1: Run a Command Only If Public Internet Is Up

* * * * * ping -W1 -c1 8.8.8.8 > /dev/null 2>&1 && /home/user/sync-cloud.sh
  • 8.8.8.8 is Google DNS — a reliable public address.
  • -W1: timeout 1 second.
  • -c1: send only one packet.
  • > /dev/null 2>&1: suppress output.
  • && /home/user/sync-cloud.sh: run the sync only if ping succeeds.

📌 This is ideal for checking if you’re connected to the internet.

🔐 Example 2: Run a Job Only If a Private Server Is Reachable

*/5 * * * * ping -W1 -c1 192.168.1.1 > /dev/null 2>&1 && /home/user/sync-nas.sh
  • 192.168.1.1 could be your NAS, router, or local server.
  • This works even without public internet, as long as your LAN is active.

📌 Great for intranet-only environments or isolated networks.

📝 Example 3: Logging Status

You can also log the result for monitoring:

* * * * * ping -W1 -c1 8.8.8.8 > /dev/null 2>&1 && echo "$(date) - Online" >> /tmp/net-status.log || echo "$(date) - Offline" >> /tmp/net-status.log

🧠 Pro Tips

  • Use full paths in cron (/bin/ping, /usr/bin/curl, etc.) if something doesn't work.
  • You can also test DNS with nslookup google.com or curl --connect-timeout 2 http://example.com for more advanced checks.

🛡️ What If You Want a Script?

Here’s a sample shell script that does the check:

#!/bin/bash 
 
TARGET="192.168.1.1"  # Can be public (8.8.8.8) or private IP 
if ping -W1 -c1 "$TARGET" > /dev/null 2>&1; then 
    /home/user/run-my-job.sh 
else 
    echo "$(date) - $TARGET not reachable" >> /var/log/netcheck.log 
fi

Then call this script from crontab:

*/10 * * * * /home/user/netcheck.sh

🧩 Final Thoughts

This method is simple, flexible, and doesn’t require installing anything extra. Whether you’re connected to a cloud server, a local NAS, or just want to ensure minimal connectivity, combining ping with cron gives you reliable conditional execution.