in reply to loop control

If you want to run the socket data flows n times every 12 hours, then you need to calculate the period, which is the inverse of the frequency.

i.e.: ntimes / 12hours
  = ntimes / 12 * 3600seconds
  = ntimes / 43200seconds
  period = 1 / frequency
  therefore period = ( 43200 / n )seconds

Using this little gem of basic mathematics, you can then proceed to recode your script:

use IO::Socket; my $sock = new IO::Socket::INET("$remote_server:43") || die $!; my $n = 5; # do this 5 times every 12 hours while (1) # loop forever { print $sock "$data\r\n"; my @output = <$sock>; $output = join('', @output); if ($output =~ /$no_match/gi) { &true; } else { &false; } # sleep for the PERIOD sleep( int(43200 / $n) ); }

Replies are listed 'Best First'.
Re^2: loop control
by jhourcle (Prior) on Dec 02, 2005 at 12:55 UTC

    One minor little 'gotcha' when dealing with cadence -- you actually want the 43200/$n to be the time between successive starts, not between the completion of one and the start of the next (ie, the time to sleep).

    To compensate, if we're dealing with something that takes any significant time to run an iteration, we need to track how long each run takes, and subtract that from the time that we're going to sleep:

    use IO::Socket; my $sock = new IO::Socket::INET("$remote_server:43") || die $!; my $n = 5; # do this 5 times every 12 hours while (1) # loop forever { my $time = time(); # keep track of when we start print $sock "$data\r\n"; my @output = <$sock>; $output = join('', @output); if ($output =~ /$no_match/gi) { &true; } else { &false; } # sleep for the PERIOD, minus the DURATION sleep( int(43200 / $n) - ( time() - $time) ); }
      cheers guys... just what I needed.. ;-)
      hi guys.. does the loop restart the tcp connection or would this remain open until i close it? is there anyway of piping the servers resonse to log with date & time etc? I don't need to wait for servers response before sending data.. cheers
      I think this is nested loops..?? if I have another loop within this routine... how can I still get the while (1) loop to work..
      my $n = 5; # do this 5 times every 12 hours while (1) # loop forever { my $time = time(); # keep track of when we start print $sock "$data\r\n"; my @output = <$sock>; $output = join('', @output); $|=1; while(<$sock>) { if ( $output is this)
      cheers steve