ThinkPHP6创建自定义定时任务命令的核心是:在app/command/目录下创建继承think\console\Command的类(如CleanLogCommand.php),命名空间为app\command,类名以Command结尾;通过php think cron:clean-log手动执行或接入Crontab自动调度。

ThinkPHP6 创建自定义定时任务命令,核心是写一个继承 think\console\Command 的类,放在 app/command/ 目录下,再通过 php think 命令名 手动触发或配合系统级定时器自动运行。
1. 创建命令类文件
在项目根目录的 app/command/ 下新建 PHP 文件,例如 CleanLogCommand.php:
- 文件路径必须为
app/command/CleanLogCommand.php(不能放子目录如app/command/cron/) - 命名空间固定为
app\command - 类名须以
Command结尾,且继承think\console\Command
2. 编写基础结构
内容示例:
namespace app\command;
<p>use think\console\Command;
use think\console\Input;
use think\console\Output;</p><p>class CleanLogCommand extends Command
{
protected function configure()
{
$this->setName('cron:clean-log')
->setDescription('清理7天前的日志文件');
}</p><pre class="brush:php;toolbar:false;">protected function execute(Input $input, Output $output)
{
$logPath = runtime_path('log/');
$files = glob($logPath . '*.log');
$cutoff = time() - 7 * 86400;
foreach ($files as $file) {
if (filemtime($file) < $cutoff) {
@unlink($file);
}
}
$output->writeln('日志清理完成。');
}}
立即学习“PHP免费学习笔记(深入)”;
-
configure()中设置命令名称(如cron:clean-log)和描述,这是后续调用的关键标识 -
execute()内写具体业务逻辑,可调用模型、缓存、数据库等框架能力 - 使用
runtime_path()获取运行时路径,避免硬编码
3. 验证与手动执行
保存后,在项目根目录运行:
php think cron:clean-log
若输出“日志清理完成”,说明命令注册成功、逻辑可执行。
注意:首次创建或修改命令类后,建议清空控制台缓存(php think clear --console),避免旧指令残留。
4. 接入系统级定时调度(如 Crontab)
在服务器上编辑定时任务:
crontab -e
添加一行(按需调整周期和路径):
0 2 * * * /usr/bin/php /var/www/myproject/think cron:clean-log >> /var/log/clean-log.log 2>&1
- 该配置表示每天凌晨2点执行
-
/usr/bin/php替换为which php实际路径 -
/var/www/myproject/think是项目根目录下的入口文件,确保有执行权限 - 日志重定向有助于排查静默失败(比如权限不足、路径错误)



















