翼度科技»论坛 编程开发 PHP 查看内容

使用ThinkPHP框架(thinkphp8.0)创建定时任的操作步骤

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
1、安装定时任务composer包
  1. composer require easy-task/easy-task
复制代码
2、创建命令行处理类文件
  1. php think make:command Task  task
复制代码
会生成文件:app\command\Task.php
将Task.php文件内容修改如下:
  1. <?php
  2. declare (strict_types=1);

  3. namespace app\command;

  4. use think\console\Command;
  5. use think\console\Input;
  6. use think\console\input\Argument;
  7. use think\console\input\Option;
  8. use think\console\Output;

  9. class Task extends Command
  10. {
  11.     protected function configure()
  12.     {
  13.         //设置名称为task
  14.         $this->setName('task')
  15.             //增加一个命令参数
  16.             ->addArgument('action', Argument::OPTIONAL, "action", '')
  17.             ->addArgument('force', Argument::OPTIONAL, "force", '');
  18.     }

  19.     protected function execute(Input $input, Output $output)
  20.     {
  21.         //获取输入参数
  22.         $action = trim($input->getArgument('action'));
  23.         $force = trim($input->getArgument('force'));

  24.         // 配置任务,每隔20秒访问2次网站
  25.         $task = new \EasyTask\Task();
  26.         $task->setRunTimePath('./runtime/');
  27.         $task->addFunc(function () {
  28.             $url = 'https://www.wushengyong.com/';
  29.             file_get_contents($url);
  30.         }, 'request', 20, 2);;

  31.         // 根据命令执行
  32.         if ($action == 'start')
  33.         {
  34.             $task->start();
  35.         }
  36.         elseif ($action == 'status')
  37.         {
  38.             $task->status();
  39.         }
  40.         elseif ($action == 'stop')
  41.         {
  42.             $force = ($force == 'force'); //是否强制停止
  43.             $task->stop($force);
  44.         }
  45.         else
  46.         {
  47.             exit('Command is not exist');
  48.         }
  49.     }
  50. }
复制代码
3、配置config\console.php文件
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 控制台配置
  4. // +----------------------------------------------------------------------
  5. return [
  6.     // 指令定义
  7.     'commands' => [
  8.         'task' => 'app\command\Task',
  9.     ],
  10. ];
复制代码
4、执行命令(windows请使用cmd):
  1. php think task start  启动命令
  2. php think task status 查询命令
  3. php think task stop   关闭命令
  4. php  think  task  stop  force   强制关闭命令
复制代码
以上就是使用ThinkPHP框架(thinkphp8.0)创建定时任的操作步骤的详细内容,更多关于ThinkPHP框架创建定时任务的资料请关注脚本之家其它相关文章!

来源:https://www.jb51.net/program/313218qca.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具