ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
Web应用在运行时会有执行时长的限制,但是实际开发中有些任务耗时比较长,甚至是常驻内存的,这时只能使用cli方式运行PHP脚本,也就是常说的命令行应用。 开发一个完整的命令行应用流程如下: ## 1、创建一个命令文件 ~~~ $ php think make:command Push Command:app\command\Push created successfully. ~~~ 成功创建后,会生成一个文件: ~~~ <?php declare (strict_types = 1); namespace app\command; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\input\Option; use think\console\Output; class Push extends Command { protected function configure() { // 指令配置 $this->setName('app\command\push') ->setDescription('the app\command\push command'); } protected function execute(Input $input, Output $output) { // 指令输出 $output->writeln('app\command\push'); } } ~~~ ## 2、添加功能 其中的 execute 方法,就是你要补充的。我给出一个我在项目中不完整的例子,如下。 ~~~ protected function execute(Input $input, Output $output) { /* 读入数据推送规则 */ $target = $input->getArgument('target'); $this->rules = Config::get('push_' . $target); $output->writeln('Push ver: ' . self::$version . PHP_EOL); if (!$this->rules) { $output->writeln('Push rules not found.'); } /* 遍历规则 */ foreach ($this->rules as $rule) { /* 启用的规则 */ if ($rule['enable'] ?? false) { /* 是否输出调试信息和调试数据 */ $rule['debug'] = $rule['debug'] ?? false; /* 获取数据 */ $data = $this->getData($rule); /* 写到目标表中 */ if (isset($rule['target'])) { $result = $this->setData($data, $rule); $output->writeln('成功数: ' . $result[0] . ', 失败数: ' . $result[1] . ',' . $rule['name'] . PHP_EOL); } } } //endforeach } ~~~ ## 3、配置命令 修改`config/console.php`文件,内容如下。 ~~~ <?php // +------------ // | 控制台配置 // +------------ return [ // 指令定义 'commands' => [ 'push' => 'app\command\Push', ], ]; ~~~ ## 4、运行命令 ~~~ php think push ~~~ 也可以用 Shell 包装以下, 让代码运行更健壮. ~~~ #!/usr/bin/env bash # 文件锁 LOCK_FILE="/var/run/push_gonggai.pid" # 日志文件 LOG_FILE="/var/log/push_gonggai.log" # 需要 root 权限 if [ "$UID" -ne "0" ]; then echo "Must be root to run this srcript." exit 103 fi if (set -o noclobber; echo "$$" > "$LOCK_FILE") 2> /dev/null; then trap 'rm -f "$LOCK_FILE"; exit $?' INT TERM EXIT echo "" >> ${LOG_FILE} echo "=== BEGIN-TO-PUSH ===" >> ${LOG_FILE} echo `date '+%Y-%m-%d %H:%M:%S'` >> ${LOG_FILE} /usr/local/php/bin/php /home/www/gonggaixitong/think push>> ${LOG_FILE} # 记录结束时间 echo `date '+%Y-%m-%d %H:%M:%S'` >> ${LOG_FILE} echo "=== END-OF-PUSH ===" >> ${LOG_FILE} echo "" >> ${LOG_FILE} rm -f $LOCK_FILE trap - INT TERM EXIT else if [ ! -f $LOCK_FILE ]; then echo "You have no right to excute the script." exit 102 else echo "The script is running, lock file is $LOCK_FILE." exit 101 fi fi ~~~ 命令行程序非常简单,脚本一旦出现错误,进程就会终止,所以需要配合进程监控工具才能使用到生产环境。本人常用的进程监控工具`pm2`及`supervisor`,大家可以关注一下。