1.使用composer安装 think-worker
composer require topthink/think-workercomposer require topthink/think-worker
2.在app\command下创建定时任务文件Cron.php(文件名自己取)
<?phpnamespace app\command;use think\console\Command;use think\console\Input;use think\console\Output;use Workerman\Lib\Timer;use Workerman\Worker;/*** 计划任务*/class Cron extends Command{protected function configure(){// 指令配置$this->setName('Cron')->setDescription('计划任务');}protected function execute(Input $input, Output $output){$worker = new Worker();$worker->name = $this->getName();$worker->onWorkerStart = function () use ($output) {//每隔24小时备份数据库$database = new Database();Timer::add((3600 * 24), [$database, 'backup'], [$output]);};Worker::runAll();}}<?php namespace app\command; use think\console\Command; use think\console\Input; use think\console\Output; use Workerman\Lib\Timer; use Workerman\Worker; /** * 计划任务 */ class Cron extends Command { protected function configure() { // 指令配置 $this->setName('Cron') ->setDescription('计划任务'); } protected function execute(Input $input, Output $output) { $worker = new Worker(); $worker->name = $this->getName(); $worker->onWorkerStart = function () use ($output) { //每隔24小时备份数据库 $database = new Database(); Timer::add((3600 * 24), [$database, 'backup'], [$output]); }; Worker::runAll(); } }
这里引用了一个 备份MYSQL的类库 点击这里
3.在配置文件config/console.php 中添加指令
‘Cron’ => ‘app\command\cron\Cron’,
<?php// +----------------------------------------------------------------------// | 控制台配置// +----------------------------------------------------------------------return [// 指令定义'commands' => ['Cron' => 'app\command\Cron',],];<?php // +---------------------------------------------------------------------- // | 控制台配置 // +---------------------------------------------------------------------- return [ // 指令定义 'commands' => [ 'Cron' => 'app\command\Cron', ], ];
4.控制台到TP目下执行以下命令
php think Cronphp think Cron
RoveCoder版权所有,转载请注明