官网文档
https://www.kancloud.cn/manual/thinkphp6_0/1037651
创建命令类文件
运行指令创建一个自定义命令类文件
php think make:command Hello hello
生成内容如下
<?php 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 Hello extends Command { protected function configure() { $this->setName('hello') ->addArgument('name', Argument::OPTIONAL, "your name") ->addOption('city', null, Option::VALUE_REQUIRED, 'city name') ->setDescription('Say Hello'); } protected function execute(Input $input, Output $output) { $name = trim($input->getArgument('name')); $name = $name ?: 'thinkphp'; if ($input->hasOption('city')) { $city = PHP_EOL . 'From ' . $input->getOption('city'); } else { $city = ''; } $output->writeln("Hello," . $name . '!' . $city); } }
配置config/console.php文件
<?php return [ 'commands' => [ 'hello' => 'app\command\Hello', ] ];
使用命令执行指令
php think hello
在宝塔面板中配置计划任务
常用指令文件
创建表
<?php declare (strict_types = 1); namespace app\command; use think\console\Command; use think\console\Input; use think\console\Output; use think\Exception; use think\facade\Db; class CreateTable extends Command { protected function configure() { // 指令配置 $this->setName('start') ->setDescription('每日创建日志数据表'); } //创建表 protected function execute(Input $input, Output $output) { $tableList = [ 'device_log' ]; foreach ($tableList as $tblpre) { // 检查今天的表 $tbldate = date('ymd'); $res = Db::execute("show tables like '{$tblpre}{$tbldate}'"); if ($res === 0) { $output->writeln('补建今天的表'.$tbldate); Db::execute("create table {$tblpre}{$tbldate} like {$tblpre}"); } //创建明天的表 try { $tblnextdate = date('ymd', strtotime('+1 day')); $res = Db::execute("show tables like '{$tblpre}{$tblnextdate}'"); if ($res === 0) { Db::execute("create table {$tblpre}{$tblnextdate} like {$tblpre}"); $output->writeln('创建明天的表'.$tblnextdate); } } catch (Exception $exception) { echo $exception->getMessage(); } } } }