Perl 在Mojolicous中渲染后做一些事情

Perl 在Mojolicous中渲染后做一些事情,perl,mojolicious,mojolicious-lite,Perl,Mojolicious,Mojolicious Lite,在HypnoToad发送一个页面后,我如何让我的代码做一些事情?(注意:我是在回答我自己的问题。我之所以发布这篇文章,是因为StackOverflow向我指出了一个没有直接解决我问题的问题,尽管它确实包含了我需要的线索。) 示例代码: use Mojolicious::Lite; get "/index" => sub { my $c = shift; $c->render("renderThis"); # Do something after rendering

在HypnoToad发送一个页面后,我如何让我的代码做一些事情?(注意:我是在回答我自己的问题。我之所以发布这篇文章,是因为StackOverflow向我指出了一个没有直接解决我问题的问题,尽管它确实包含了我需要的线索。)

示例代码:

use Mojolicious::Lite;
get "/index" => sub {
   my $c = shift;
   $c->render("renderThis");
   # Do something after rendering
};
app->start('daemon', '-l', 'http://*:8080');

__DATA__
@@ renderThis.html.ep
% layout  "template" ;
<h1>Hello World</h1>

@@ layouts/template.html.ep
<!DOCTYPE html>
<html><head></head><body>
%= content
</body></html>
我使用的是win7,因此只有unix的解决方案不起作用。

中的解决方案对我不起作用。(也就是说,西蒙尼在他的评论中链接到的答案。我没有尝试mob提供的fork解决方案。)我的线索来自Саа27的评论。以下是我的解决方案:

use Mojolicious::Lite;
use Mojo::IOLoop;
get "/index" => sub {
   my $c = shift;
   $c->render("renderThis");
   Mojo::IOLoop->timer(0 => sub {
      sleep 15;
      say "That was a long time, but at least the page got sent quickly.";
   });
};
app->start('daemon', '-l', 'http://*:8080');

__DATA__
@@ renderThis.html.ep
% layout  "template" ;
<h1>Hello World</h1>

@@ layouts/template.html.ep
<!DOCTYPE html>
<html><head></head><body>
%= content
</body></html>
使用Mojolicious::Lite;
使用Mojo::IOLoop;
获取“/索引”=>sub{
我的$c=班次;
$c->render(“renderThis”);
Mojo::IOLoop->timer(0=>sub{
睡眠15;
说“那是一段很长的时间,但至少页面发送得很快。”;
});
};
app->start('daemon','-l','http://*:8080');
__资料__
@@renderThis.html.ep
%布局“模板”;
你好,世界
@@layouts/template.html.ep
%=内容
计时器将其代码从调用方的执行流中取出,因此调用函数在计时器代码执行之前完成并清除其缓冲区(即使time参数比调用方完成所需的时间短)


注意:我从实验中得到了解释,而不是代码检查,所以我不知道调用方是否在计时器运行其代码之前刷新了所有缓冲区。我只知道render的http响应发出,并且在计时器代码运行之前,STDOUT被刷新到控制台。我概括了这些观察结果,得出了上述结论。

您可以将代码附加到。大多数其他方法都不能保证等待响应实际发送,因为它是以异步方式发生的

use Mojolicious::Lite;
get "/index" => sub {
   my $c = shift;
   $c->render("renderThis");
   $c->tx->on(finish => sub {
      sleep 15; # this is a really bad idea, use a timer instead
      say "That was a long time, but at least the page got sent quickly.";
   });
};

非常感谢。这正是我想要的。我仍然有点喜欢我的黑客解决方案,…因为它是黑客。但你的答案绝对是正确的。我确实发现,使用计时器时,我必须在时间槽中放入一个小数字,以使实际代码正常工作。我最终使用了.01而不是0。
use Mojolicious::Lite;
get "/index" => sub {
   my $c = shift;
   $c->render("renderThis");
   $c->tx->on(finish => sub {
      sleep 15; # this is a really bad idea, use a timer instead
      say "That was a long time, but at least the page got sent quickly.";
   });
};