How can I schedule a cron job that runs every 10 seconds in linux?

Solution 1:

I had a similar task last week. My solutions was to multiply the standard cron entries to the desired frequency. My crontab looks like:

* * * * * /usr/local/bin/php /var/www/myscript.php
* * * * * sleep 10; /usr/local/bin/php /var/www/myscript.php
* * * * * sleep 20; /usr/local/bin/php /var/www/myscript.php
* * * * * sleep 30; /usr/local/bin/php /var/www/myscript.php
* * * * * sleep 40; /usr/local/bin/php /var/www/myscript.php
* * * * * sleep 50; /usr/local/bin/php /var/www/myscript.php

If you want to check results of myscript.php, e.g. for debugging, just append

&> /tmp/myscipt.log

to each line in the crontab above. Then stderr and stdout get redirected to the log file.

Solution 2:

You can't schedule the job every ten seconds, but I suppose you could schedule the job to run every minute, and sleep in a loop in 10s intervals. This would be predicated on your command being completed before the ten second interval expires, or you'll get overlap when the next command runs. This feels like a precarious solution, but if you can guarantee very short execution of the main command of the script, it would work.

#!/bin/bash
i=0

while [ $i -lt 6 ]; do
  /run/your/command &
  sleep 10
  i=$(( i + 1 ))
done

Tags:

Linux

Unix