Thursday, February 26, 2026

How to run a command or script at regular intervals in Linux. Any alternative for crontab?

 To run a Linux command every 5 seconds, you have a few reliable options depending on what you prefer: watch, a while loop, or using cron (though cron can only go as low as 1 minute).

Here are the best methods 👇


✅ 1. Using watch (simplest method)

watch -n 5 <your-command>

Example:

watch -n 5 ls -l

➡️ Runs ls -l every 5 seconds and shows the output updating on screen.


✅ 2. Using an infinite while loop

This gives more control, supports complex commands, and works in any shell.

while true; do
    <your-command>
    sleep 5
done

Example:

while true; do
    date
    sleep 5
done


✅ 3. Using a one-liner while loop

while true; do <your-command>; sleep 5; done

Example:

while true; do curl -I https://example.com; sleep 5; done


🚫 Cron? Not suitable

Cron runs at minimum 1-minute intervals, so it cannot run every 5 seconds.


To run a cron job every 1 minute, you can use the * * * * * syntax in your crontab.

Here’s how to set it up 👇


✅ Step 1: Open the crontab

crontab -e


✅ Step 2: Add a cron entry with 1‑minute interval

Use this format:

* * * * * <your-command>

Example: run a script every minute:

* * * * * /home/user/myscript.sh

Example: append timestamp to a log every minute:

* * * * * echo "$(date)" >> /home/user/time.log


✅ Step 3: Save and exit

  • If using nanoCTRL + O, then CTRL + X
  • If using vim:wq

📝 Tips and Best Practices

1️⃣ Redirect output to avoid cron emails

* * * * * <your-command> >/dev/null 2>&1

2️⃣ Ensure the script is executable

chmod +x /home/user/myscript.sh

3️⃣ Use full paths in cron

Cron runs in a limited environment, so:

❌ Avoid:

python3 script.py

✔️ Use:

/usr/bin/python3 /home/user/script.py



Featured

TechBytes on Linux

This is a growing list of Linux commands which might come handy for the of Linux users. 1. Found out i had to set the date like this: ...

Popular Posts