重新启动Perl脚本错误?(Perl新手)



我正在使用从CPAN获得的AnyEvent::Twitter::Stream模块。我也是一个Perl新手,我从示例中修改的这个脚本触发一个事件,以便在基于某些条件从twitter流API读取tweet时将一些twitter数据插入数据库。我已经编辑了一些代码,但一般信息如下:

#!/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 "pingn";
          },
        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} . " Storedn";
                } 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;
    },

这似乎没有重新启动进程。有谁能给我提供点建议吗?

我不熟悉这个模块,但是您需要更清楚地了解"流或应用程序将因为仍然迷惑我的原因而退出"是什么意思。脚本会死吗?

如果是,捕获错误并重新启动的一种方法是将整个代码包装在eval中,如下所示:

my $continue = 1;
while ($continue) {
   eval {  # Catch "die" event
       my $streamer = xxx
       # some other call to start the streamer???
   };
   if ($@ =~ /specific error message substring you wish to restart on/) {
       # Do some prep work if needed
   } else {
       $continue = 0; # quit on next loop iteration
       # As alternative to using $continue flag, just do:
       # last; 
   }
}

相关内容

  • 没有找到相关文章

最新更新