0

-callback中的附加代码:content_cb会减慢下载速度吗?

假设附加代码需要 1_000/1_000_000 秒才能运行并且回调被调用 1_000 次,那会减慢 1_000/1_000_000 * 1_000 秒的下载速度吗?

#!/usr/bin/env perl
use warnings;
use 5.012;
use Time::HiRes qw(usleep);
use File::Basename;
use LWP::UserAgent;

my $url = 'my_url';
my $file_name = basename $url;
my $ua = LWP::UserAgent->new();

open my $fh, '>>:raw', $file_name or die $!;
my $res = $ua->get( 
    $url,
    ':content_cb' => sub { 
        my ( $chunk, $res, $proto ) = @_;
        print $fh $chunk; 
        usleep( 1000 ); # code substitute
    },
);
close $fh;
4

1 回答 1

2

我建议使用HTTP::Async模块。

use HTTP::Async;

my $url = 'http://...';
my $async = HTTP::Async->new;

$async->add( HTTP::Request->new( GET => $url ) );

while ( my $response = $async->wait_for_next_response ) {
  # Do some processing with $response
}
于 2012-04-12T14:24:27.827 回答