Abbacabba has asked for the wisdom of the Perl Monks concerning the following question:

I'm writing a daemon for a company production system and need to know if this will come back to bite my butt.

I was wanting a way to make sure this daemon sleeps properly so I don't chew up valuable CPU time.

I'm catching and using signals and found that sleep gets "woken up" whenever a child signals in.

When I want to sleep in my prog I do this now:
1. define a variable to keep track of actual time spent sleeping. ($slept)
2. in my main loop, reset $slept to 0
3. loop until my $slept is equal or greater than my specified sleep interval ($Interval)
4. wash, rinse, repeat
my $slept; my $Interval = 120; while(1) { check_signals(); $slept = 0; while($slept <= $Interval) { $slept += sleep(60); } }
The only thing I see here is that I might end up sleeping for $Interval + 59 seconds, which is fine with me. Does anyone feel uneasy about this code?

Replies are listed 'Best First'.
Re: Tracking actual time spent sleeping: Is this bad coding?
by dragonchild (Archbishop) on Feb 02, 2005 at 15:12 UTC
    I don't see a huge issue with that. You could improve it by changing the sleep(60) to sleep( $Interval - $slept + 1 ).

    But, that begs the question - why aren't you using your system's version of cron?

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

      Dunno about the OP but I have a daemonized process that monitors some hardware and sleeps a lot. I do not use cron though because the start up costs are high compared to the actual work it does.

      Cheers,
      R.

      Pereant, qui ante nos nostra dixerunt!
        If you're worried about the startup costs of cron, I've had excellent experiences with Schedule::Cron. You can daemonize the process and tell it to run a coderef on schedule.
        I'm unfamiliar with any start-up costs of cron. I use it quite frequently on most boxes I administer. Would you mind going into detail? Perhaps after your explanation I'll change my ways.

        - Justin