We help IT Professionals succeed at work.

Making a script repeat

jillybabe
jillybabe asked
on
Hi

I need a simple solution for a script that runs, writes to a dB and then exits to NOT exit but start again at the beginning and continue doing so ad infinitum.

Can anyone tell me the best way to do this please?

thanks

Jilly
Comment
Watch Question

Commented:
hmmm

while(1)
{
# write in database
  write_in_db();
# sleep for five seconds
  sleep(5);
}

Author

Commented:
Hi

That works great thanks but can you tell me why it works - I am blonde so be gentle with the explanation ?

:-)

Jilly

Commented:
okz

while(1)
# a while loop remains looping until the condition between the ( and ) renders false. But because 1 always renders true, the loop will never end.
{
  write_in_db();
# sleep(x) will delay execution for x seconds. Without this your script will run like crazy ;-)
  sleep(5);
}

Author

Commented:
Wow it's easy when you know how :-)

If I wanted it to run 10 times and stop is it similar?

Jilly

Commented:
If you'd only want to do it ten times, you're better off with a for loop:

my $iWriteDelay=5;

for (my $iIndex=0; $iIndex<10; $iIndex++)
{
  &vWriteToDb;

  sleep ($iWriteDelay);
}
Commented:
To loop for 10 times, you would get the following:

# This defines a for loop, which consists of three parts, the initialisation ($i=0), the condition ($i<10) which works the same as the while loop condition and the action part ($i++), which in this case increments $i when all statements between the brackets have been executed.

for ($i=0;$i<10;$i++)
{
# $i < 10 yields true, so we can still execute some code here
  write_in_db();
  sleep(5);
# at this time the value of $i will be incremented.
}

Author

Commented:
Fantastic you really have helped me

thanks a lot

Jilly

Explore More ContentExplore courses, solutions, and other research materials related to this topic.