我们使用composer 下载好tp6, 默认你已经完成,我的在这里了
Win10下面, 在当前文件夹目录窗口,左上角 :文件---》打开window powershell, 这个可以理解为高级版的DOS窗口, 没有的直接打开dos窗口也行
1、预备:确保你的composer正常,检测下,输出版本号试试,能输出来 就可以
2、在TP6目录下,直接导入workerman模块,执行命令
composer require workerman/workerman
执行后, 在TP6根目录下面的vendor目录下,会多一个workerman目录,下面有文件。
3、创建 Timer 命令
你会在app/command 目录下看到Timer.php文件
内容长这样的
你写你的逻辑,在
<?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; use Workerman\Worker; class Timer extends Command { protected $timer; protected $interval = 2; protected function configure() { // 指令配置 $this->setName('timer') ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections') ->addOption('d', null, Option::VALUE_NONE, 'daemon(守护进程)方式启动') ->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次') ->setDescription('开启/关闭/重启 定时任务'); } protected function init(Input $input, Output $output) { global $argv; if ($input->hasOption('i')) $this->interval = floatval($input->getOption('i')); $argv[1] = $input->getArgument('status') ?: 'start'; if ($input->hasOption('d')) { $argv[2] = '-d'; } else { unset($argv[2]); } } protected function execute(Input $input, Output $output) { // 指令输出 $output->writeln('timer'); $this->init($input, $output); //创建定时器任务 $task = new Worker(); $task->count = 1; ///安排你的事情 AAA //.....start $t = date('Y-m-d H:i:s',time()); file_put_contents('./work_log.html',"[$t] hello,开始吧! ".PHP_EOL,FILE_APPEND); //...end $task->onWorkerStart = [$this, 'start']; $task->runAll(); } public function stop() { \Workerman\Lib\Timer::del($this->timer); } public function start() { $last = time(); $task = [6 => $last, 10 => $last, 30 => $last, 60 => $last, 180 => $last, 300 => $last]; $this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) { //每隔2秒执行一次 try { $now = time(); ///安排你的事情 BBB //.....start $t = date('Y-m-d H:i:s',time()); file_put_contents('./work_log.html',"[$t] hello,试试! ".PHP_EOL,FILE_APPEND); //...end foreach ($task as $sec => $time) { if ($now - $time >= $sec) { //每隔$sec秒执行一次 ///安排你的事情 CCC //.....start $t = date('Y-m-d H:i:s',time()); file_put_contents('./work_log.html',"[$t] hello,foreach循环了! ".PHP_EOL,FILE_APPEND); //...end $task[$sec] = $now; } } } catch (\Throwable $e) { } }); } }
4、注册 Timer 命令
修改TP6配置目录里的 console.php 文件,关联到这个Timer.php
5、启动Timer,......
Nice!!!!,
6、基于是零基础学习,如果按我步骤来, 遇到这个报错, 就是您没有引入worker, 加上
解决:
搞定!
=================起来 是 起来了=================================
怎么安排它做事呢?
如上源码,可以换成你的逻辑代码
运行结果:
(end)
附加学习:
1、composer命令删除一个包的命令,
composer remove workerman/workerman
2、composer命令 自我更新的命令
composer self-update