This code works like a charm... but I have a few questions before I
replicate it for a few other uses...
The idea is to do a DB request at regular intervals and send the result to
any listening websockets.
It feels 'funny' because I have to get a reference to the app from the
first subscriber.
- this is a subclass of Controller - how do I a reference to the app from
my own controller in the IOLoop subroutine?
- I thought the IOLoop set-up should go in a BEGIN block but that doesn't
seem to work. Is there some other way I can/should run code at init?
- is it okay to run a few of these IOLoops in different packages? Is there
some better pattern?
Am I doing anything crazy here?
Thanks for any thoughts!
package UserInterface::Pipeline;
use Mojo::Base 'Mojolicious::Controller';
use Mojo::IOLoop;
use Time::HiRes;
use UserInterface::Util::JobUtils;
my $refreshRate = 5;
my @subscribers;
my $myApp;
###############################################
# setup the recurring loop to collect updates
###############################################
Mojo::IOLoop->recurring($refreshRate => sub {
if (@subscribers){ # only do this if someone is listening
my $response = {
timestamp => time,
response => "pipelineUpdate",
data => &_collectData()
};
for my $s(@subscribers){
$s->send({json => $response});
}
}
});
sub socket {
my $self = shift;
if (! $myApp){
$myApp = $self->app;
$refreshRate = $self->app->config->{"pipelineRefreshRateSeconds"};
}
push(@subscribers, $self);
$self->on( finish => sub {
my ($self, $code, $reason) = @_;
@subscribers = grep { $_ != $self } @subscribers;
});
$self->send({json => { response => "subscribed pipeline", refreshRate =>
$refreshRate }});
}
sub _collectData {
my $retVal;
if ($myApp){
$retVal = $myApp->job_db->selectall_hashref( "do SQL stuff");
} else {
$retVal = "ERROR: server side -> myApp not populated!";
}
return $retVal;
}
1;
--
You received this message because you are subscribed to the Google Groups
"Mojolicious" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/mojolicious.
For more options, visit https://groups.google.com/d/optout.