How to run scripts every 5 seconds?
Solution 1:
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.
Solution 2:
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?
Solution 3:
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.
Solution 4:
You could use the GNU package mcron, a "Vixie cron" alternative.
http://www.gnu.org/software/mcron/manual/mcron.html#Top
"Can easily allow for finer time-points to be specified, i.e. seconds. In principle this could be extended to microseconds, but this is not implemented."
Solution 5:
You could use a SystemD timer unit, which will trigger a service - that you'd set up to do what you want - every 5 seconds.
Suppose your service unit is called mystuff.service
and is installed in /etc/systemd/system
(check out SystemD user services if you want to replace a user's crontab), then you can write a timer unit to run the service at boot time and then every 5 seconds, like this:
/etc/systemd/system/mystuff.timer
[Unit]
Description=my stuff's schedule
[Timer]
OnBootSec=5
OnUnitActiveSec=5
[Install]
WantedBy=timers.target
Then reload the systemd configuration, enable the timer unit and start it.