[TriLUG] Starting and stopping jobs with cron

Neil Roeth neil at occamsrazor.net
Sat Dec 11 17:26:44 EST 2004


On Dec  9, Victor Snesarev (vnsnes at yahoo.com) wrote:
 > Here's the situation... I start a process using cron, but I need to kill 
 > that process one hour later using cron. There doesn't seem to be a 
 > crontab option to run a command for a specified period of time. I 
 > suppose I could set an environment variable at the start of the process 
 > containing the process ID and an hour later use that environment 
 > variable as an argument to "kill", but I do not know a way to retrieve 
 > the process ID.
 > 
 > Would it be easy to parse "ps | grep <command_name>" or is there an 
 > better way to do this?
 > 
 > Any suggestions?

You can create a wrapper script that starts the main job in the background,
saves the pid of the background process, sleeps for an hour, then kills the
background process.

For example, assume your process is started with a script called main.sh.
Create wrapper.sh like so:

------------------------------------------------------------
#!/bin/bash

main.sh &
BACKPID=$!
sleep 3600
kill -9 $BACKPID
------------------------------------------------------------

Instead of a call to main.sh in your crontab, put a call to wrapper.sh.  No
temp files need to be written and it requires only a single cron entry.

-- 
Neil Roeth



More information about the TriLUG mailing list