I want to schedule a command like ./example
every 6 minutes and when 6 minutes is done it exits the process and runs it again. How would I do that in Bash? I run CentOS.

- 90,431
- 16
- 141
- 175

- 39
- 1
- 4
-
Why does this have upvotes? At all? – tripleee Oct 08 '15 at 19:23
2 Answers
I would make a cronjob running every sixth minutes and using the timeout
command to kill it after, say, 5 minutes and 50 seconds.
This is a sample crontab rule:
*/6 * * * * cd /path/to/your/file && timeout -s9 290s ./example
It changes working directory to where you have your script and then executes the script. Note that I send it signal 9 (SIGKILL) using the -s9
flag which means "terminate immediately". In most cases you might want to consider sending SIGTERM instead, which tells the script to "exit gracefully". If that is the case you can consider giving the script a little bit more time to exit by decreasing the timeout value even more. To send SIGTERM instead of SIGKILL, just remove the -s9
flag.
You edit your crontab by running crontab -e

- 90,431
- 16
- 141
- 175
Replace mycommand
in the script below...
#! /bin/bash
## create an example command to launch for demonstration purposes
function mycommand { D=$(date) ; while true ; do echo $D; sleep 1s ; done; }
while true
do
mycommand & PID=$!
sleep 6m
kill $PID ; wait $PID 2>/dev/null
done
Every six minutes, this kills the command then restarts it.
Use Ctrl-C as one way to terminate this sequence.

- 51,587
- 17
- 154
- 173
-
Of course, this solution should be monitored by systemd, supervisord or similar. – Emil Vikström Oct 07 '15 at 14:09
-
@EmilVikström: You might want to do that if this is *mission critical*. You might not want to bother with it otherwise. – Brent Bradburn Oct 07 '15 at 14:15