Search code examples
bashcroncron-task

Running CRON every 10 seconds


I have to run certain CRON every 10 seconds. I have following two methods to achieve what I want.

Method 1

Running same cron multiple times each with sleep 10 seconds.

* * * * * php /path/to/php/file/to/execute >> /path/to/logs/logfile.log
* * * * * sleep 10; php /path/to/php/file/to/execute >> /path/to/logs/logfile.log
* * * * * sleep 20; php /path/to/php/file/to/execute >> /path/to/logs/logfile.log
* * * * * sleep 30; php /path/to/php/file/to/execute >> /path/to/logs/logfile.log
* * * * * sleep 40; php /path/to/php/file/to/execute >> /path/to/logs/logfile.log
* * * * * sleep 50; php /path/to/php/file/to/execute >> /path/to/logs/logfile.log

Method 2

Using sh. File Cron.sh has following code

#!/bin/bash

while true; do
  php /path/to/php/file/to/execute
  sleep 10
done

Make Cron.sh file executable chmod +x Cron.sh

Run script in background ./Cron.sh &

Question

Which of these two methods is better in terms of performance and overall?

Thanks


Solution

  • The two methods are actually different.

    • Method 1 one will start 5 jobs at approximately the same time, run the sleep command and execute the jobs at about the desired time-offset.
    • Method 2 will trigger the sleep 10 after a job finished. This implies that it will not run every 10 seconds, but every 10 seconds plus the run-time of the job.

    Besides the timing:

    • Method 1 will run all jobs, independ of any of the other jobs. So there is the certainty that all jobs will run.
    • Method 2 might terminate all remaining jobs in certain circumstances.

    Method 1 might have some issues with race-conditions to the log-file.