如何让 DBD::Pg 可靠地超时?
为什么这段代码直到 $sth->execute 完成之后才执行信号处理程序?更重要的是,我该如何解决它?
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use Sys::SigAction qw( set_sig_handler );
my $dbh = DBI->connect('dbi:Pg:dbname=dc');
eval {
my $h = set_sig_handler('ALRM', sub { die "timeout\n" });
eval {
alarm 1;
my $sth = $dbh->prepare("SELECT pg_sleep(10)");
print "Before execute\n";
$sth->execute;
print "After execute\n";
$sth->finish;
};
alarm 0;
die "$@" if $@;
};
die "$@" if $@;
print "Finished\n";
Why doesn't this code execute the signal handler until after $sth->execute completes? And more importantly, how can I fix it?
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use Sys::SigAction qw( set_sig_handler );
my $dbh = DBI->connect('dbi:Pg:dbname=dc');
eval {
my $h = set_sig_handler('ALRM', sub { die "timeout\n" });
eval {
alarm 1;
my $sth = $dbh->prepare("SELECT pg_sleep(10)");
print "Before execute\n";
$sth->execute;
print "After execute\n";
$sth->finish;
};
alarm 0;
die "$@" if $@;
};
die "$@" if $@;
print "Finished\n";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑使用 Pg 的异步查询功能。
Consider using Pg's asynchronous query feature instead.
由于 Perl 处理信号的方式发生了变化(从 5.8.0 开始称为“安全信号”),您需要使用 Perl::Unsafe::Signals 允许您的
die()
在$sth-> 时工作;执行
正在进行中。Due to changes in the way Perl handles signals (so-called "safe signals" as of 5.8.0), you'll need to use Perl::Unsafe::Signals to allow your
die()
to work when$sth->execute
is in progress.有 AnyEvent::Pg 允许异步查询 PostgreSQL,但它与 DBI 不兼容它会迫使您在 AnyEvent 之上重写您的应用程序/脚本。
There is AnyEvent::Pg that allows to query PostgreSQL asynchronously, though, it is not DBI compatible and it will force you to rewrite your app/script on top of AnyEvent.