PHP code example of mle86 / wq

1. Go to this page and download the library: Download mle86/wq library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mle86 / wq example snippets




use mle86\WQ\Job\AbstractJob;

class EMail extends AbstractJob
{
    protected $recipient;
    protected $subject;
    protected $message;
    
    public function __construct(string $recipient, string $subject, string $message)
    {
        $this->recipient = $recipient;
        $this->subject   = $subject;
        $this->message   = $message;
    }
    
    public function send()
    {
        if (mail($this->recipient, $this->subject, $this->message)) {
            // ok, has been sent!
        } else {
            throw new \RuntimeException ("mail() failed");
        }
    }
}



use mle86\WQ\WorkServerAdapter\BeanstalkdWorkServer;

$mailJob = new EMail("[email protected]", "Hello?", "This is a test mail.");

$workServer = BeanstalkdWorkServer::connect("localhost");
$workServer->storeJob("mail", $mailJob);



use mle86\WQ\WorkServerAdapter\BeanstalkdWorkServer;
use mle86\WQ\WorkProcessor;

$queue = "mail";
printf("%s worker %d starting.\n", $queue, getmypid());

$processor  = new WorkProcessor(BeanstalkdWorkServer::connect("localhost"));
$fn_handler = function(EMail $mailJob) {
    $mailJob->send();
    // don't catch exceptions here, or the WorkProcessor won't see them.
};

while (true) {
    try {
        $processor->processNextJob($queue, $fn_handler);
    } catch (\Throwable $e) {
        echo $e . "\n";  // TODO: add some real logging here
    }
}