【发布时间】:2015-07-28 15:38:22
【问题描述】:
我有一个通常需要 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;
}
&do_the_subroutine 永远不会返回,所以我无法继续前进。我也无法将这段代码放入该子程序中。有什么想法吗?
【问题讨论】:
-
能分享一下子程序的代码吗?它对我来说很好用,请看这个演示:ideone.com/KycD4S
-
我似乎无法重现这种行为,使用我看到警报响起的相同代码。还有更多我们在这里没有看到的代码吗?你能说明
do_the_subroutine的定义吗? -
OLE 的东西看起来可能很慢。
-
@pilcrow 这个问题与 CR 无关。这是关于寻找已知的错误并更改代码的功能。请阅读A Guide to Code Review for Stack Overflow users
-
FWIW perlmonks.org/?node_id=505473 似乎也表明 OLE 不能很好地处理警报。也许将工作转移到子进程或线程?
标签: perl time timeout ole subroutine