[TriLUG] Starting and stopping jobs with cron

Mike Broome mbroome at employees.org
Thu Dec 9 22:00:32 EST 2004


You can combine the fact that you know your PID in the environment
variable $$ with being able to schedule a job to run at a specific time
in the future (say, 1 hour) using at to do what you're asking.

Here's a quick and dirty sample script that shows how it might be done:

=====

#!/bin/bash

# test of setting a timer to kill the current process

echo "my PID is $$"

# create file of commands for at to run
echo "kill $$" > /tmp/kill-myself.$$
# schedule the job
at -f /tmp/kill-myself.$$ now + 1 minute
# remove the file of commands
rm /tmp/kill-myself.$$

# go off and do something
echo "Going to sleep ..."
sleep 10000
echo "Woke up."

exit

=====

And here's the output from running the script:

[mike at neo tmp]$ ./kill-test
my PID is 5592
warning: commands will be executed using (in order) a) $SHELL b) login
shell c) /bin/sh
job 4 at 2004-12-09 21:58
Going to sleep ...
Terminated
[mike at neo tmp]$


Mike

On Thu, Dec 09, 2004 at 07:33:13PM -0500, Victor Snesarev 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?
> 
> TIA,
> Victor

-- 
Mike Broome
mbroome(at)employees.org



More information about the TriLUG mailing list