我正在使用从 CPAN 获得的 AnyEvent::Twitter::Stream 模块。我也是 Perl 的新手,我从示例中修改的这个脚本会触发一个事件,一旦基于某些条件从 Twitter 流 API 读取一条推文,就会将一些推特数据插入数据库。我已经编辑了一些代码,但一般信息如下:
#!/usr/bin/perl
use strict;
use AnyEvent::Twitter::Stream;
use DBI;
use DBD::mysql;
my $done = AnyEvent->condvar;
my($user, $password, $method, $args) = @ARGV;
# my twitter login
my %args;
if ($method eq 'follow') {
$args{follow} = $args;
$method = 'filter';
} elsif ($method eq 'track') {
$args{track} = $args;
$method = 'filter';
}
binmode STDOUT, ":utf8";
my $streamer = AnyEvent::Twitter::Stream->new(
username => $user,
password => $password,
timeout => 0,
method => $method || "sample",
%args,
on_keepalive => sub {
warn "ping\n";
},
on_tweet => sub {
my $DBIconnect;
#db connection info
my $dsn = "dbi:mysql:$database:$host:$dbport";
$DBIconnect = DBI->connect($dsn, $db_user, $db_pass);
my $tweet = shift;
if($tweet->{id}) {
# occasionally twitter
# insert some data here
my $save_tweet = $query;
#print $query;
my $save_handle = $DBIconnect->prepare($save_tweet);
if($save_handle->execute()) {
#print "Tweet #" . $tweet->{id} . " Stored\n";
} else {
#print "Error Saving Tweet #" . $tweet->{id} . "\n";
}
$save_handle->finish();
$DBIconnect->disconnect();
} else {
#print "Tweet did not contain Tweet ID.\n";
}
},
on_error => sub {
my $error = shift;
print "Error! Error!";
warn "ERROR: $error";
$done->send;
sleep 2;
$done->recv;
},
on_eof => sub {
$done->send;
},
);
$done->recv;
在这个过程中,有时流或应用程序会退出,原因仍然让我感到困惑。我想简单地等待 3 秒,然后重新启动整个 perl 脚本(或只是 AnyEvent 实例)以继续读取数据。
您可能会注意到我尝试过这样做:
on_error => sub {
my $error = shift;
print "Error! Error!";
warn "ERROR: $error";
$done->send;
sleep 2;
$done->recv;
},
这似乎不会重新启动该过程。谁能告诉我这需要什么?