- 创建自定义命令类文件
php think make:command Test
会生成app\command\Test.php命令行指令类,如下
<?php
declare(strict_types=1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class Test extends Command
{
protected function configure()
{
// 指令配置,定义了一个叫test的命令,运行php think test即可执行execute()方法
$this->setName('test')
->setDescription('the test command');
}
// 要执行的具体代码逻辑
protected function execute(Input $input, Output $output)
{
// 指令输出
$output->writeln('test');
}
}
- 在config/console.php中注册命令
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
// 指令定义
'commands' => [
'test' => 'app\command\Test',
],
];
- 运行命令
php think // 终端命令查看
php think test // 执行命令
- 编写linux contrab定时文件,将注册命令添加到定时任务中
步骤:
# 进入编辑状态
crontab -e
# 添加执行任务
2 0 * * * /www/server/php/81/bin/php /www/wwwroot/wanglvdu/wanglvdu_api/think 任务名称 >> /tmp/cron_error.log
# 保存退出后重启crontab
/etc/init.d/crond restart
// '2 0 * * *' 时间任务配置
// '/www/server/php/81/bin/php' php路径
// '/www/wwwroot/wanglvdu/wanglvdu_api/think signup' 文件地址
// '>> /tmp/cron_error.log' 错误日志输出
crontab基本命令:
# ubuntu
systemctl status cron // 查看状态
systemctl start cron // 启动
systemctl restart cron // 重启
# centos
systemctl status crond // 查看状态(注意有d)
...
# crontab
crontab -l // 查看命令
crontab -e // 编辑命令
crontab -r // 删除任务
# crontab 时间格式
minute hour day month week command
分 小时 天 月 星期 命令
eg:
0 0 * * * command 每天执行一次
0 0 * * 0 command 每周执行一次
0 0 1 0 0 command 每月执行一次