How to run scripts every 5 seconds?

Cron only allows for a minimum of one minute. What you could do is write a shell script with an infinite loop that runs your task, and then sleeps for 5 seconds. That way your task would be run more or less every 5 seconds, depending on how long the task itself takes.

#!/bin/bash

while true; do
  # Do something
  sleep 5;
done

You can create a my-task.sh file with the contents above and run it with sh my-task.sh. Optionally you can configure it with supervisor as a service so that it would start when the system boots, etc.

It really does sound like you're doing something that you probably shouldn't be doing though. This feels wrong.


You could have a cron job kick-off a script every minute that starts 12 backgrounded processes thusly:

* * * * * ~/dostuff.sh

dostuff.sh:

(sleep 5 && /path/to/task) &
(sleep 10 && /path/to/task) &
(sleep 15 && /path/to/task) &
(sleep 20 && /path/to/task) &
(sleep 25 && /path/to/task) &
(sleep 30 && /path/to/task) &
(sleep 35 && /path/to/task) &
(sleep 40 && /path/to/task) &
(sleep 45 && /path/to/task) &
(sleep 50 && /path/to/task) &
(sleep 55 && /path/to/task) &
(sleep 60 && /path/to/task) &

My question, though, is What on EARTH could you be doing that needs to run every 5 seconds?


Just use a loop:

while true ; do ./your-script & sleep 5; done

This will start your-script as a background job, sleep for 5 seconds, then loop again. You can use Ctrl-C to abort it, or use any other condition instead of true, e.g. ! test -f /tmp/stop-my-script to only loop while the file /tmp/stop-my-script does not exist.

Tags:

Cron

Scripts