[NTLUG:Discuss] Simple way to repeat command every 'x' seconds

Rob Apodaca rob.apodaca at attbi.com
Mon Apr 14 07:47:58 CDT 2003


On Mon, 14 Apr 2003 08:23:52 -0500
"Jack Snodgrass" <jack+ntlug at mylinuxguy.net> wrote:

> I want to be able to do something like
> do forever
>    du -H -s 
>    sleep 20 seconds 
> loop
> 
> from the command line with a simple command. Is there something 
> already out there that does this, or do I have to write a script? 
> 

Hi Jack,
If you are ok to use perl, here is a stripped down version of a script I
use to poll a directory for files every n seconds. It has a signal
handler so you can kill it nicely. I believe I got most of this from a
book but, it was so long ago when I wrote it that I really can't
remember.
Also, I use an init script to start and stop so it runs kind of like a
daemon.
It may be a bit crude but it has worked for a few years now.

Cheers,
-Rob

---
#!/usr/bin/perl

#length of time to sleep
my $sleep = 15;

# Fork and then let the parent exit
$pid = fork;
exit if $pid;
die "could not fork: $!" unless defined($pid);

#Disassociate from the controlling terminal
use POSIX;

POSIX::setsid()
        or die "cant start a new session: $!";

#Set initial time to die variable       
$time_to_die = 0;

#sub to reset time to die variable
sub signal_handler
{
        $time_to_die = 1;
}

#trap signals
$SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&signal_handler;

until ($time_to_die) #loop until receiving a kill signal
{
        #put your stuff to do here
        sleep $sleep; #sleep for specified period of time
}
print "ive been killed\n";



More information about the Discuss mailing list