PHP code example of piotrek-r / worker

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

    

piotrek-r / worker example snippets


$worker = new \PiotrekR\Worker\Worker();

$worker->run(function () {
    // do something
});

$workerConditions = new \PiotrekR\Worker\WorkerConditions(
    timeSeconds: 10,
);

$worker = new \PiotrekR\Worker\Worker($workerConditions);

$worker->run(function () {
    // do something
});

$workerConditions = new \PiotrekR\Worker\WorkerConditions(
    memoryLimit: '512m',
);

$worker = new \PiotrekR\Worker\Worker($workerConditions);

$worker->run(function () {
    // do something
});

$workerConditions = new \PiotrekR\Worker\WorkerConditions(
    countLoops: 100,
);

$workerConditions = new \PiotrekR\Worker\WorkerConditions(
    countHandled: 5,
);

$workerConditions = new \PiotrekR\Worker\WorkerConditions(
    countEmpty: 1,
);

$workerConfiguration = new \PiotrekR\Worker\WorkerConfiguration(
    sleepMicrosecondsAfterHandled: 1000, // 1ms to get quick to the next item
    sleepMicrosecondsAfterEmpty: 5000000, // 5s to not spam the queue
);

$worker = new \PiotrekR\Worker\Worker(null, $workerConfiguration);

$worker->run(function () {
    // do something
});

$arg1 = 'foo';
$arg2 = 'bar';
$arg3 = 3;

$worker = new \PiotrekR\Worker\Worker();

$worker->run(function (string $arg1, string $arg2, int $arg3) {
    echo $argument;
    return true;
}, $arg1, $arg2, $arg3);

use PiotrekR\Worker\Worker;
use PiotrekR\Worker\WorkerConditions;
use PiotrekR\Worker\WorkerConfiguration;

$queue = new ThirdPartyQueueHandler();

$workerConditions = new WorkerConditions(
    timeSeconds: 10,
    memory: '512m',
);

$workerConfiguration = new WorkerConfiguration(
    sleepMicrosecondsAfterHandled: 1000,
    sleepMicrosecondsAfterEmpty: 1000000,
);

$worker = new Worker($workerConditions, $workerConfiguration);

$result = $worker->run(function (ThirdPartyQueueHandler $queue) {
    return $queue->handleNextMessage();
}, $queue);

printf(
    "It took %d seconds to loop %d times. Of which %d were handled, and %d were empty.\n",
    $result->getTimeElapsed(),
    $result->getCountLoops(),
    $result->getCountHandled(),
    $result->getCountEmpty(),
);