2

I have a LAMP setup in Docker to act as an API for a Cordova project I'm developing.

I've only just looked into PHP enqueuing and RabbitMQ but offloading tasks would be a major help to speed up tasks like photo upload or email sending.

I have this code to listen and consume RabbitMQ messages for sending emails, however I'm not sure how to launch this as a kind of daemon with PHP. I also plan on adding further queue's which would require further listeners so my idea is to have a Docker task container dedicated to listening for and consuming tasks.

use Enqueue\AmqpLib\AmqpConnectionFactory;
use Enqueue\AmqpLib\AmqpContext;

/**
 * Inititate queue
 */
emailQueue();

function emailQueue(){
    // Create consumer
    $context = (new AmqpConnectionFactory(ENQUEUE_OPTIONS))->createContext();
    $queue = $context->createQueue('send_email');
    $context->declareQueue($queue);
    $consumer = $context->createConsumer($queue);

    while(true) {
        // Get message
        $message = $consumer->receive($timeout = 10);

        if($message) {
            // Extract args
            $args = json_decode($message->getBody(), true);
            extract($args);

            // Send email
            $mail = new Mailer();
            $mail->setFrom($from, $from_name);
            $mail->addAddress($email);
            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->send();

            // Acknowledge
            $consumer->acknowledge($message);
        }
    }
}

How can I create a Docker container that will launch my PHP scripts to listen and consume the PHP tasks so as to not block my main app execution?

2
  • too late but maybe help others : you can create Cron job run flock your script Jun 6, 2019 at 12:11
  • @aminmahmoudi Cron didn't work in my case as the moment there was a failure it died and the container was shutdown, supervisord gave a more manageable approach with monitoring
    – Arran
    Jun 7, 2019 at 2:49

1 Answer 1

0

I ended up following the tutorial given here https://docs.docker.com/config/containers/multi-service_container/

Using supervisord I was able to schedule several PHP task consumer scripts with auto-restarts on failure and logging to the Docker logs file for monitoring.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.