投递任务

Testing Is Documentation

tests/Protocol/TaskTest.php投递任务 - 图1

任务投递是对 Swoole 官方的简单封装。

Uses

  1. <?php
  2. use Leevel\Protocol\Task;
  3. use Swoole\Process;
  4. use Swoole\Server;
  5. use Throwable;

投递异步任务

投递单个异步任务。

  1. public function testTask(): void
  2. {
  3. $process = new Process(function (Process $worker) {
  4. try {
  5. $swooleServer = new Server('127.0.0.1', 10000);
  6. $swooleServer->set([
  7. 'worker_num' => 1,
  8. 'task_worker_num' => 1,
  9. ]);
  10. $swooleServer->on('Start', function (Server $server) use ($worker) {
  11. });
  12. $swooleServer->on('Receive', function ($req, $rep) {
  13. });
  14. $swooleServer->on('Task', function (Server $serv, $task_id, $from_id, $data) {
  15. });
  16. $task = new Task($swooleServer);
  17. $task->task('taskWillNotRun');
  18. } catch (Throwable $exception) {
  19. $worker->write('Exception Thrown: '.$exception->getMessage());
  20. }
  21. $worker->exit();
  22. });
  23. $process->start();
  24. $output = $process->read();
  25. Process::wait(true);
  26. $this->assertSame('Exception Thrown: Swoole\\Server::task(): server is not running', $output);
  27. }

并发执行任务并进行协程调度

支持多个任务并发执行,底层进行协程调度。

  1. public function testTaskCo(): void
  2. {
  3. $process = new Process(function (Process $worker) {
  4. try {
  5. $swooleServer = new Server('127.0.0.1', 10000);
  6. $swooleServer->set([
  7. 'worker_num' => 1,
  8. 'task_worker_num' => 1,
  9. ]);
  10. $swooleServer->on('Start', function (Server $server) use ($worker) {
  11. });
  12. $swooleServer->on('Receive', function ($req, $rep) {
  13. });
  14. $swooleServer->on('Task', function (Server $serv, $task_id, $from_id, $data) {
  15. });
  16. $task = new Task($swooleServer);
  17. $task->taskCo(['taskWillNotRun']);
  18. } catch (Throwable $exception) {
  19. $worker->write('Exception Thrown: '.$exception->getMessage());
  20. }
  21. $worker->exit();
  22. });
  23. $process->start();
  24. $output = $process->read();
  25. Process::wait(true);
  26. $possiableMessage = [
  27. 'Exception Thrown: Swoole\\Server::taskCo(): server is not running',
  28. 'Exception Thrown: Swoole\\Server::taskCo(): taskCo method can only be used in the worker process',
  29. ];
  30. $this->assertTrue(in_array($output, $possiableMessage, true));
  31. }