http://www.perlmonks.org?node_id=24427

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

I would like to know how to create a perl programme that will run forever, something like a timer where it will push or copy a certain file to another directory at a certain hour everyday.

The timer i tried before, ran every second. Resource over-utilized is not the biggest concern, its only the second. The thing is that, my timer version runs for every second in that minute. Can i make it run like once in that minute i choose it to run?

my version timer that i used, utilizes a FOR loop. Is there a better way of coding it and also making it run once in that minute i specify.

Originally posted as a Categorized Question.

  • Comment on What is the best way to run periodic tasks (once per minute)?

Replies are listed 'Best First'.
Re: What is the best way to run periodic tasks (once per minute)?
by Corion (Patriarch) on Jul 26, 2000 at 12:53 UTC

    First of all, most operating systems already have services for scheduling program runs. UNIX has the cron program and Windows NT has the AT program and service. Look first into these before you think of rolling your own.

    If you still want to roll your own, look into the sleep() function call, which will put your script to sleep for the amount of time you specify. Note that running such a script on a server without the administrators knowledge could have bad consequences for you. First talk to your admin and think if using cron would do the job for you as well.

    Here is a small program that prints a line every 10 seconds (tested) :

    #!/usr/bin/perl -w use strict; my $tick = "tick\n"; # loop until this process is terminated from the outside while (1) { print $tick; # Make "tick" into "tock" and "tock" into "tick" $tick =~ tr/io/oi/; # sleep 10 seconds sleep( 10 ); }

Re: What is the best way to run periodic tasks (once per minute)?
by qi3ber (Scribe) on Jul 26, 2000 at 18:01 UTC
    Corion is correct. A modification that I have had to make on several occasions allows for more time intensive tasks is this:

    while (1) { $waketime = time + $sleep_duration; &do_complex_things; sleep($waketime-time); }


    Something else that you might want to look into is the Time::HiRes module.
      A more Unix-y way to do this would be to use the alarm function. See 'perldoc -f alarm' for details.
      #!/usr/bin/perl use strict; my $interval = 60; # seconds between calls + # sub will be called every $interval seconds my $process = sub { print "processing!\n" }; + # engage the alarm system $SIG{ALRM} = sub { &$process; alarm $interval; }; + alarm $interval; + # function will be called every 60 seconds for rest of program...

      Another alternative would be to upgrade the program to use POE events. This would be the route I would take. The alarm demo is more for historical interest and fiddling than for anything else.