创建进程

fastd 内部进程依赖 swoole,因此在使用该功能前,请确保当前 swoole 环境是否已经成功安装。

创建进程,仅需两步:

  • 创建进程类: 进程所执行的逻辑
  • 注册到配置文件: config/process.php值得注意的是,进程中如果需要保持在后台运行,需要在进程中设置"死循环",让其一直执行,否则会在逻辑代码执行完成后,进程退出。
  1. <?php
  2. namespace Process;
  3. use FastD\Process\AbstractProcess;
  4. use swoole_process;
  5. class HelloProcess extends AbstractProcess
  6. {
  7. public function handle(swoole_process $swoole_process)
  8. {
  9. timer_tick(1000, function ($id) {
  10. static $index = 0;
  11. ++$index;
  12. echo $index.PHP_EOL;
  13. if ($index === 3) {
  14. timer_clear($id);
  15. }
  16. });
  17. }
  18. }

以上程序每秒输出 $index,直到 $index == 3 时,进程退出,父进程进行回收。

注册到配置文件中(config/process.php):

  1. <?php
  2. return [
  3. 'demo' => [
  4. 'process' => \Process\HelloProcess::class,
  5. 'options' => [
  6. ],
  7. ],
  8. ];
  1. $ php bin/console process demo

输出:

  1. process demo pid: 15894
  2. pid: fastd-demo/runtime/process/demo.pid
  3. 1
  4. 2
  5. 3
  6. process: demo. pid: 15894 exit. code: 0. signal: 0

process 命令包含几个命令,可以通过 -h 进行查看:

  1. $ php bin/process -h
  1. Usage:
  2. process [options] [--] [<process>] [<action>]
  3. Arguments:
  4. process process name
  5. action process action, status|start|stop [default: "status"]
  6. Options:
  7. -p, --pid[=PID] set process pid path.
  8. --name[=NAME] set process name.
  9. -d, --daemon set process daemonize.
  10. -h, --help Display this help message
  11. -q, --quiet Do not output any message
  12. -V, --version Display this application version
  13. --ansi Force ANSI output
  14. --no-ansi Disable ANSI output
  15. -n, --no-interaction Do not ask any interactive question
  16. -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  17. Help:
  18. Create new processor.

除了可以单独运行外,还能直接注入到 swoole server 中执行。😎