1

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.

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
Dayne Jones
  • 39
  • 1
  • 4

2 Answers2

6

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

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
2

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.

Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173