I used the Mojo::Pg module as an example.
--MyApp.pm--
package MyApp;
use Mojo::Base 'Mojolicious';
use Mojo::Pg;
# This method will run once at server start
sub startup {
my $self = shift;
# Documentation browser under "/perldoc"
$self->plugin('PODRenderer');
$self->config(hypnotoad => {workers => 4});
$self->helper(pg => sub{ state $pg = Mojo::Pg->new('postgresql://jlzhang@/db1')});
$self->pg->pubsub->listen(
foo => sub {
my ($pubsub, $payload) = @_;
say $$;
});
# Router
my $r = $self->routes;
# Normal route to controller
$r->get('/')->to('example#welcome');
}
1;
--Example.pm--
package MyApp::Controller::Example;
use Mojo::Base 'Mojolicious::Controller';
# This action will render a template
sub welcome {
my $self = shift;
$self->pg->pubsub->notify(foo => 'PostgreSQL rocks!');
# Render template "example/welcome.html.ep" with message
$self->render(msg => 'Welcome to the Mojolicious real-time web framework!');
}
1;
--hypnotoad -f script/my_app--
[Tue Oct 25 08:23:42 2016] [info] Listening at "http://*:8080"
Server available at
http://127.0.0.1:8080[Tue Oct 25 08:23:42 2016] [info] Manager 16422 started
[Tue Oct 25 08:23:42 2016] [info] Creating process id file "/home/jlzhang/tmp/my_app/script/hypnotoad.pid"
16426
There is 4 workers, but only one print process id.
I try to use Mojo::IOLoop::Delay:
Mojo::IOLoop->delay(
sub {
$self->pg->pubsub->listen(
foo => sub {
my ($pubsub, $payload) = @_;
say $$;
});
});
--hypnotoad -f script/my_app--
[Tue Oct 25 08:37:47 2016] [info] Listening at "http://*:8080"
Server available at
http://127.0.0.1:8080[Tue Oct 25 08:37:47 2016] [info] Manager 16594 started
[Tue Oct 25 08:37:47 2016] [info] Creating process id file "/home/jlzhang/tmp/my_app/script/hypnotoad.pid"
16595
16596
16597
16598
Yes, all workers print process id.
How does hypnotoad handle the startup function?
BTW.
Use Mojo::IOLoop::Delay in a statup function, does this comply with the specification?