perlmqttanyevent

Keep a perl script running


I have a perl script that subscribes to a message queue using AnyEvent::MQTT.

At the minute all I want it to do is print out when it get's a message. I'm totally new to perl so I'm using the demo code it comes with which includes a bit that publishes anything on the STDIN as a message - this works great, and I can see all the messages received.

This code looks as follows

#!/usr/bin/perl
use strict;
use warnings;

use AnyEvent::MQTT;
my $mqtt = AnyEvent::MQTT->new;
my $cv = $mqtt->subscribe(topic => '/AlarmMode',
                           callback => sub {
                               my ($topic, $message) = @_;
                                       print $topic, ' ', $message, "\n"
                                   });

my $qos = $cv->recv; # subscribed, negotiated QoS == $qos



  # publish line-by-line from file handle
      $cv =  $mqtt->publish(handle => \*STDIN,
                            topic => '/topic');

The issue I have is that if I remove everything after the comment publish line-by-line from file handle then my app exits as soon as it's ran.

I've tried including a while loop that sleeps for 5 seconds but that does't work (the app just looks like it's hung).

I know I need to do something to tell the app just to stay alive and chill, but I don't know what that command is :-)


Solution

  • If you block with something that isn't AE-aware (e.g. sleep), then AE events won't be handled.

    To sleep while allowing the AE events to be handled, one normally uses

    my $done_cv = AE::cv;
    $done_cv->recv;
    

    Use $done_cv->send; to end the sleep. For example, If you wanted to sleep for 5 seconds, you'd use

    my $sleep_cv = AE::cv;
    my $w = AE::timer(5, 0, $sleep_cv);  # Short for AE::timer(5, 0, sub { $sleep_cv->send });
    $sleep_cv->recv;