PHP code example of myclabs / work

1. Go to this page and download the library: Download myclabs/work 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/ */

    

myclabs / work example snippets


$workDispatcher = new RabbitMQWorkDispatcher(/* parameters */);
$workDispatcher->run(new MyTask());

// my-worker.php
$worker = new RabbitMQWorker(/* parameters */);
// Will loop continuously and execute tasks
$worker->work();

class BigComputation implements MyCLabs\Work\Task\Task
{
    public $parameter1;
}

class BigComputationExecutor implements MyCLabs\Work\TaskExecutor\TaskExecutor
{
    public function execute(Task $task)
    {
        if (! $task instanceof BigComputation) {
            throw new \Exception("Invalid task type provided");
        }
        // Perform the action (here we just multiply the parameter by 2)
        return $task->parameter1 * 2;
    }
}

interface SynchronousWorkDispatcher extends WorkDispatcher
{
    /**
     * Run a task in background.
     *
     * You can use $wait to wait a given time for the task to complete.
     * If the task hasn't finished during this time, $timedout will be
     * called and this method will return.
     * If the task has finished, $completed will be called.
     *
     * @param Task     $task
     * @param int      $wait      Number of seconds to wait for the task to complete.
     *                            If 0, doesn't wait.
     * @param callable $completed Called (if $wait > 0) when the task has completed.
     * @param callable $timedout  Called (if $wait > 0) if we hit the timeout while
     *                            waiting.
     * @param callable $errored   Called (if $wait > 0) if the task errors. Takes 1
     *                            parameter which is the exception.
     *
     * @return void No results
     */
    public function runAndWait(
        Task $task,
        $wait = 0,
        callable $completed = null,
        callable $timedout = null,
        callable $errored = null
    );
}
shell
$ php my-worker.php