首页 > 解决方案 > 如何在 Perl 中为长时间运行的 Sybase sp 设置超时

问题描述

我正在调用一个存储过程,它在 Perl 中从 Sybase DB 中删除数据。但是 sp 需要几个小时才能完成。我只想让 sp 运行 1 小时,然后无论它是否完成,我都希望之后的代码能够运行。我该如何实施?

sub DelRef {
    print "starting defRefData\n";
    $db = new Sybapi($user, $password, $server, $margin_database); 
    #the following sql will take hours
    $db->exec_sql("exec CPN_Margins..clean_up_refData_db '$XrefCode'");
}

&DelRef();
print "process is done\n";
$db->close();

标签: perltimeoutsybase

解决方案


我总是对使用alarm中断系统调用持谨慎态度,因为我发现很难预测信号何时会被忽略或更糟

另一种方法是在后台进程中运行长时间运行的代码,并在主进程中监视其进度。

# DelRef() might take a while ...
my $start_time = time;
my $pid = fork();
if ($pid == 0) {
    # child process
    DelRef();
    exit 0;
}
# parent process
while (1) {
    use POSIX qw( WNOHANG );
    my $waitpid = waitpid $pid, WNOHANG;
    if ($pid == $waitpid) {
        print STDERR "DelRef() finished successfully\n";
        last;
    }
    if (time - $start_time > 3600) {
        print STDERR "DelRef() didn't finish in an hour\n";
        kill 'TERM',$pid;    # optional
        last;
    }
    print STDERR "DelRef() is still running ...\n";
    sleep 60;
}
print STDERR "... the rest of the script ...\n";

推荐阅读