我有 perl 应用程序,例如,在 google 中进行并行搜索:
use Mojo::UserAgent;
use Mojo::IOLoop;
my $ua = Mojo::UserAgent->new();
my $delay = Mojo::IOLoop->delay(sub { say 'DONE1 (should be before render)'; });
foreach my $i ( 1 .. 10 ) {
$delay->begin();
$ua->get("http://www.google.ru/search?q=$i" => sub {
say $i;
$delay->end();
});
}
$delay->wait() unless $delay->ioloop->is_running();
say 'DONE2 (should be before render)';
say 'Found! (render)';
它工作正常:
6
1
7
10
3
9
2
5
8
4
DONE1 (should be before render)
DONE2 (should be before render)
Found! (render)
当我在 Controller 的 Mojolicious 应用程序中使用此代码时:
package MyApp::Google;
use Mojo::Base 'Mojolicious::Controller';
sub search {
my $self = shift;
my $delay = Mojo::IOLoop->delay(sub { $self->app->log->debug('DONE1 (should be before render)') });
foreach my $i ( 1 .. 10 ) {
$delay->begin();
$self->ua->get("http://www.google.ru/search?q=$i" => sub {
$self->app->log->debug($i);
$delay->end();
});
}
$delay->wait() unless $delay->ioloop->is_running();
$self->app->log->debug('DONE2 (should be before render)');
return $self->render_text('Found!');
}
走错了路:
[Wed May 15 11:07:32 2013] [debug] Routing to controller "MyApp::Google" and action "search".
[Wed May 15 11:07:32 2013] [debug] DONE2 (should be before render)
[Wed May 15 11:07:32 2013] [debug] 200 OK (0.005689s, 175.778/s).
[Wed May 15 11:07:32 2013] [debug] 1
[Wed May 15 11:07:32 2013] [debug] 8
[Wed May 15 11:07:32 2013] [debug] 10
[Wed May 15 11:07:32 2013] [debug] 5
[Wed May 15 11:07:32 2013] [debug] 3
[Wed May 15 11:07:32 2013] [debug] 9
[Wed May 15 11:07:32 2013] [debug] 6
[Wed May 15 11:07:32 2013] [debug] 2
[Wed May 15 11:07:32 2013] [debug] 4
[Wed May 15 11:07:32 2013] [debug] 7
[Wed May 15 11:07:32 2013] [debug] DONE1 (should be before render)
我想是这样 $delay->wait()
不是在等待。为什么会这样?
最佳答案
在这种情况下,您需要通过从 Controller 调用方法 render_later 来禁用自动渲染。 ( http://mojolicio.us/perldoc/Mojolicious/Controller#render_later )
只需将下一个字符串添加到search Controller :
$self->render_later;
完整示例:
#!/usr/bin/perl -wl
use Mojolicious::Lite;
get '/' => sub {
my $self = shift;
$self->render_later;
my $delay = Mojo::IOLoop->delay(sub {
$self->app->log->debug('Delay finished!');
$self->render(text => 'test!');
});
for my $i (0 .. 5) {
my $end = $delay->begin;
Mojo::IOLoop->timer($i => sub {
$self->app->log->debug($i);
$end->();
});
}
};
app->start;
https://stackoverflow.com/questions/16558940/
相关文章:
google-drive-api - 我如何将文件上传到我拥有具有编辑权限的共享链接的 Google
chef-infra - 是否有相当于 Berkshelf 的产品,但用于 Puppet 模块?
vba - 如何将 Microsoft Word 中当前选定段落的段落编号获取到 AppleScri
events - Kendo multiselect,当一个项目被移除时触发一个事件
haskell - Tree(Int,Int) 在 haskell 中是什么意思?
db2 - SQLRPGLE 中 OPEN 游标上的 SQL -302
itextsharp - 使用 iTextSharp.ShowTextAligned() 添加水印