Perl子例程超时

ans*_*rio 6 perl time timeout ole subroutine

我有一个子程序,通常需要1秒才能运行.有时,它可以无限运行.如果子程序花费的时间太长(> 10秒)并且忽略该子程序的运行,我想继续执行代码.这是我到目前为止使用的警报.

use Win32::OLE;

eval { 
    local $SIG{ALRM} = sub { die "alarm\n" };
    alarm 10;                   # schedule alarm in 10 seconds 
    &do_the_subroutine;
    alarm 0;                    # cancel the alarm
};

if ($@) {
    $error_string .= $script;
    #Do something else if the subroutine took too long.
}

do_the_subroutine{
# use existing instance if Excel is already running
    eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
    die "Excel not installed" if $@;
    unless (defined $ex) {
        $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
                or die "Oops, cannot start Excel";
    }

    # get a new workbook
    $book = $ex->Workbooks->Add;

    # write to a particular cell
    $sheet = $book->Worksheets(1);
    $sheet->Cells(1,1)->{Value} = "foo";

    # write a 2 rows by 3 columns range
    $sheet->Range("A8:C9")->{Value} = [[ undef, 'Xyzzy', 'Plugh' ],
                                       [ 42,    'Perl',  3.1415  ]];

    # print "XyzzyPerl"
    $array = $sheet->Range("A8:C9")->{Value};
    for (@$array) {
        for (@$_) {
            print defined($_) ? "$_|" : "<undef>|";
        }
        print "\n";
    }

    # save and exit
    $book->SaveAs( 'test.xls' );
    undef $book;
    undef $ex;
}
Run Code Online (Sandbox Code Playgroud)

&do_the_subroutine永远不会返回,所以我无法继续前进.我也无法将这段代码放在该子程序中.有什么想法吗?

dpw*_*dpw 4

我怀疑你想要做的事情在 Windows 上根本不可能实现alarm

perldoc perlport

Alarm 使用定时器进行模拟,只要 Perl 想要发送“安全信号”,就必须显式轮询定时器,因此不能中断阻塞的系统调用。(Win32)