Skip to content

Instantly share code, notes, and snippets.

@ubermuda
Created December 17, 2019 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ubermuda/3cab1c6eb4d3428e092cfc5bcc6b6c0b to your computer and use it in GitHub Desktop.
Save ubermuda/3cab1c6eb4d3428e092cfc5bcc6b6c0b to your computer and use it in GitHub Desktop.
<?php
use Clue\React\Mq\Queue;
use React\Promise\Promise;
class Job
{
public function run()
{
return new Promise(function() {
echo 'foo'.PHP_EOL;
sleep(1);
});
}
}
$q = new Queue(3, null, static function(Job $job) {
return $job->run();
});
$i = 0;
$q(new Job());
$q(new Job());
$q(new Job());
@ace411
Copy link

ace411 commented Dec 17, 2019

Decent attempt. First, try to stay averse to writing long-running blocking code inside the event-loop (sleep in this case). Otherwise, I think a better example should be:

class Job {
  private $count = 0;
  public function job(int $x)
  {
    return new Promise(fn(callable $res) => $res($this->count + $x));
  }
}

$loop = \React\EventLoop\Factory::create();

$q = new Queue(3, array_combine(['first', 'second'], range(1, 2)), fn($x) => (new Job)->job($x)); //evaluates to a Promise

$q->then(
  function (array $res) {
    print_r($res); 
  },
  function ($err) {
    print_r($err->getMessage());
  }
);

$loop->run();

Also, remember to have the loop running every time you run the queue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment