How To Run A Cron Job Every 10 Seconds In Linux?

Published August 19, 2024

Problem: Running Cron Jobs More Frequently Than Once Per Minute

Cron jobs in Linux usually run at intervals of one minute or longer. Sometimes, you need to run tasks more often, like every 10 seconds. This can be a problem for tasks that need to run almost instantly.

Using Multiple Cron Entries with Sleep Commands

Setting Up the Cron Jobs

To run a task every 10 seconds in Linux, you can use multiple cron entries with sleep commands. This method uses six cron entries that run every minute, each with a different sleep duration. By spacing out the execution times, you can get a 10-second interval between each task run.

The process involves:

  1. Creating six cron entries that run every minute
  2. Adding sleep commands to each entry to offset the execution time
  3. Using the same command for each entry

Here's an example of these cron entries:

* * * * * /usr/bin/wget http://api.us/application/
* * * * * sleep 10; /usr/bin/wget http://api.us/application/
* * * * * sleep 20; /usr/bin/wget http://api.us/application/
* * * * * sleep 30; /usr/bin/wget http://api.us/application/
* * * * * sleep 40; /usr/bin/wget http://api.us/application/
* * * * * sleep 50; /usr/bin/wget http://api.us/application/

In this setup, the first entry runs at the start of each minute. The next entries use sleep commands to delay their execution by 10, 20, 30, 40, and 50 seconds. This creates a pattern where the command runs every 10 seconds throughout each minute.

This method helps you work around cron's one-minute limit and run your task at 10-second intervals.

Tip: Logging Cron Job Execution

To monitor the execution of your cron jobs and verify they're running at the correct intervals, add a logging command to each entry. For example:

* * * * * /usr/bin/wget http://api.us/application/ && echo "$(date): Job executed" >> /var/log/cron_job.log
* * * * * sleep 10; /usr/bin/wget http://api.us/application/ && echo "$(date): Job executed" >> /var/log/cron_job.log

This will create a log file with timestamps for each job execution, helping you track and debug your cron setup.