ThinkPHP6定时任务命令支持命令行传参,需在configure()中用addArgument()和addOption()定义参数与选项,execute()中通过$input->getArgument()和$input->getOption()获取;调用时参数不加短横线、选项加--前缀,Crontab中须cd项目根目录并用绝对路径执行。

ThinkPHP6 的定时任务命令(即继承 think\console\Command 的类)支持通过命令行直接传参,参数可在 execute() 方法中获取,无需额外解析。关键在于正确配置参数类型(必填/可选)、定义名称,并在调用时按规范传入。
定义带参数的命令
使用 php think make:command 创建命令后,在 configure() 方法中添加参数声明:
-
必填参数:用
Argument::REQUIRED,例如订单 ID -
可选参数:用
Argument::OPTIONAL或Option::VALUE_OPTIONAL,例如指定环境或批次大小 - 参数名不加短横线(如
order_id),选项名需加短横线(如--env)
示例(app/command/SendNotice.php):
protected function configure()
{
$this->setName('notice:send')
->setDescription('发送系统通知')
->addArgument('user_id', Argument::REQUIRED, '用户ID,必须提供')
->addOption('template', 't', Option::VALUE_OPTIONAL, '通知模板标识,默认 use_default', 'use_default')
->addOption('dry-run', null, Option::VALUE_NONE, '仅模拟执行,不真实发送');
}
在 execute 中读取参数
Input 对象提供统一方法获取:
-
$input->getArgument('user_id')→ 获取必填/可选参数值 -
$input->getOption('template')→ 获取选项值 -
$input->hasOption('dry-run')→ 判断是否启用了开关类选项
示例逻辑片段:
protected function execute(Input $input, Output $output)
{
$userId = $input->getArgument('user_id');
$template = $input->getOption('template');
$isDryRun = $input->hasOption('dry-run');
<pre class="brush:php;toolbar:false;">if ($isDryRun) {
$output->writeln("【模拟】将向用户 {$userId} 发送模板 {$template} 的通知");
return 0;
}
// 实际调用服务发送
(new NoticeService())->send($userId, $template);
$output->success("通知已发送");
}
调用方式与 Crontab 配合
命令行直接运行(测试用):
php think notice:send 12345 --template=welcome php think notice:send 67890 --dry-run
Crontab 中调用(注意路径和参数固定):
# 每天上午9点给用户1001发公告 0 9 * * * cd /var/www/myapp && /usr/bin/php think notice:send 1001 --template=announcement >> /var/log/notice_cron.log 2>&1
若需动态参数(如从数据库查出一批 ID),建议封装为 shell 脚本调用 PHP 命令循环执行,避免 Crontab 表达式硬编码参数。
常见注意事项
- 参数名和选项名区分大小写,且不能含空格或特殊符号
- Crontab 中路径必须用绝对路径,
cd切换目录是安全做法 - 日志重定向推荐用
>>追加,避免覆盖;可配合date生成日期文件名 - 敏感参数(如 token、密钥)不应出现在命令行中,应改用配置或环境变量注入
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











