queue.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. use Channel\Client;
  3. use Channel\Server;
  4. use Workerman\Worker;
  5. use Workerman\Timer;
  6. // composer autoload
  7. include __DIR__ . '/../vendor/autoload.php';
  8. $channel_server = new Server();
  9. $worker = new Worker();
  10. $worker->name = 'Event';
  11. $worker->onWorkerStart = function()
  12. {
  13. Client::connect();
  14. $count = 0;
  15. $timerId = Timer::add(0.01, function() use (&$timerId, &$count) {
  16. Client::publish('test event', 'some data');
  17. $count++;
  18. Client::enqueue('task-queue', time());
  19. if ($count == 1000) {
  20. Timer::del($timerId);
  21. }
  22. });
  23. Timer::add(10, function() {
  24. Client::enqueue('task-queue', 'hello every 10 seconds');
  25. });
  26. };
  27. $mq = new Worker();
  28. $mq->name = 'Queue';
  29. $mq->count = 4;
  30. $mq->onWorkerStart = function($worker) {
  31. Client::connect();
  32. $countDown = 20;
  33. $id = 1;
  34. Client::watch('task-queue', function($data) use ($worker, &$countDown, &$id) {
  35. echo "[$id] Worker {$worker->id} get queue: $data\n";
  36. sleep(0.2);
  37. $countDown--;
  38. $id++;
  39. if ($worker->id > 1 && $countDown == 0) {
  40. Client::unwatch('task-queue');
  41. }
  42. Timer::add(1, [Client::class, 'reserve'], [], false);
  43. });
  44. };
  45. Worker::runAll();