How can I tell Perl to run some code every 20 seconds?

后端 未结 8 809
余生分开走
余生分开走 2021-02-13 15:45

How can I tell Perl to run some code every 20 seconds?

相关标签:
8条回答
  • 2021-02-13 16:33

    Set up a SIGALRM handler, and send yourself a signal every 20 seconds with alarm (see perldoc -f alarm):

    $SIG{ALRM} = sub {
        # set up the next signal for 20 seconds from now
        alarm 20;
    
        # do whatever needs to be done
        # ...
    };
    

    This will experience drift over time, as each signal may be delayed by up to a second; if this is important, set up a cron job instead. Additionally, even more drift will happen if your other code takes upwards of 20 seconds to run, as only one timer can be counting at once. You could get around this by spawning off threads, but at this point, I would have already gone back to a simple cron solution.

    Choosing the proper solution is dependent on what sort of task you need to execute periodically, which you did not specify.

    0 讨论(0)
  • 2021-02-13 16:34

    It is better to use some event library. There are a couple of choices:

    IO::Async::Timer::Periodic

    use IO::Async::Timer::Periodic;
    
    use IO::Async::Loop;
    my $loop = IO::Async::Loop->new;
    
    my $timer = IO::Async::Timer::Periodic->new(
       interval => 60,
    
       on_tick => sub {
          print "You've had a minute\n";
       },
    );
    
    $timer->start;
    
    $loop->add( $timer );
    
    $loop->run;
    

    AnyEvent::DateTime::Cron

    AnyEvent::DateTime::Cron->new()
        ->add(
            '* * * * *'   => sub { warn "Every minute"},
            '*/2 * * * *' => sub { warn "Every second minute"},
          )
        ->start
        ->recv
    

    EV::timer

    etc.

    0 讨论(0)
提交回复
热议问题