Last Updated: February 25, 2016
·
14.98K
· djuki

Run scripts on Linux/Ubuntu every few seconds, faster than Cron can do it.

With Cron you can run php scripts every minute but not in shorter period of time. So what can you do when you need to run your script every 15 seconds or even 1 second ?

Create shell sctipt like this one fasterthancron.sh

#!/bin/bash
#This script run every 15 seconds
while (sleep 15 && php /path_to_script/faster_than_cron.php) &
do
  wait $!
done

Make this file executable. This script is improved thanks to becreative-germany - see comments.

$sudo chmod +x /path_to/faster_than_cron.sh

Now this script need to be run by system when it boots, so lets change some linux files now. File /etc/rc.local is starting with system, so we can add additionsl scripts it can run. Lets edit this file now.

$sudo nano /etc/rc.local

Add this line into this file before exit 0 line.

sh /path_to/faster_than_cron.sh

Now reboot your system. This can be used to run any kind of scripts or commands on your system.

4 Responses
Add your response

Use more secure method (sleep 15 && command ...) & to ensure that the interval is finished and use & for executing the command asynchronously in a subshell.

over 1 year ago ·

I have not much knowledge about linux shell scripting but with some minutes i found out that there are many things you must know before you use it as cron alternative:

  1. Your Script execute in the main shell process so the shell is completely blocked I think cause the semicolon behind the while statement (In my case restart was necessary)
  2. To ensure that the job execute in a subshell you must use the & for executing the command asynchronously but you must also wait for this subprocess with ẁait $!

This works nice:

while [ 1 ]
do
(sleep 5 && php /home/Username/Desktop/test.php) &
wait $!
done
over 1 year ago ·

Sorry @Ivan Đurđevac but this method is even more elegant ^^

while (sleep 5 && php /home/user/desktop/test.php) &
do
wait $!
done
over 1 year ago ·

We have a winner :) Its mush better, and trick with & running in separate thread is very important. Thanks.

over 1 year ago ·