1

我有一个调用可能长时间运行的进程的应用程序。我希望我的程序,这个过程的调用者,在任何给定点取消它,并在超过时间限制时继续下一个条目。使用 Perl 的 AnyEvent 模块,我尝试了这样的事情:

#!/usr/bin/env perl

use Modern::Perl '2017';
use Path::Tiny;
use EV;
use AnyEvent;
use AnyEvent::Strict;

my $cv = AE::cv;
$cv->begin;  ## In case the loop runs zero times...

while ( my $filename = <> ) {
    chomp $filename;
    $cv->begin;

    my $timer = AE::timer( 10, 0, sub {
        say "Canceled $filename...";
        $cv->end;
        next;
    });

    potentially_long_running_process( $filename );
    $cv->end;
}

$cv->end;
$cv->recv;

exit 0;

sub potentially_long_running_process {
    my $html = path('foo.html')->slurp;
    my @a_pairs = ( $html =~ m|(<a [^>]*>.*?</a>)|gsi );
    say join("\n", @a_pairs);
}

问题是长时间运行的进程永远不会超时并被取消,它们只是继续运行。所以我的问题是“我如何使用 AnyEvent(和/或相关模块)来超时一个长期运行的任务?”

4

1 回答 1

1

您没有提到运行此脚本的平台,但如果它在 *nix 上运行,您可以使用 SIGALRM 信号,如下所示:

my $run_flag = 1;

$SIG{ALRM} = sub {
    $run_flag = 0;
}

alarm (300);

while ($run_flag) {
    # do your stuff here
    # note - you cannot use sleep and alarm at the same time
}

print "This will print after 300 seconds";
于 2017-12-01T03:47:08.767 回答