ThinkPHP 5.1定时任务通过封装数据库操作至命令类execute()方法实现,需创建app\command\CheckDeviceHeartbeat类,配置cron:check-device命令,手动测试后用crontab每2分钟调用php think指令执行。

ThinkPHP 5.1 的定时任务本身不直接“操作数据库”,而是通过你编写的命令逻辑来调用数据库方法。关键在于把业务逻辑(比如查、删、更新)写进命令类的 execute() 方法里,并确保环境和连接正常。
创建可执行的数据库操作命令类
这是最常用也最推荐的方式:将数据库操作封装为命令行指令,再由系统 crontab 定时触发。
- 在
application/command/目录下新建文件,例如CheckDeviceHeartbeat.php - 命名空间必须是
app\command,类名与文件名一致,继承think\console\Command -
configure()中设置命令名(如cron:check-device)和描述 -
execute()中写真实逻辑,可直接使用\think\Db::table()或模型操作数据库
示例:检查超时设备并记录日志
以下是一个典型场景——每2分钟查一次无心跳设备,并插入告警记录:
<?php namespace app\command;
<p>use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;<p>class CheckDeviceHeartbeat extends Command
{
protected function configure()
{
$this->setName('cron:check-device')
->setDescription('检查设备心跳,超时设备写入告警表');
}</p><pre class="brush:php;toolbar:false;">protected function execute(Input $input, Output $output)
{
$twoMinutesAgo = time() - 120;
// 查询2分钟内无心跳的设备
$timeoutDevices = Db::name('device')
->where('last_heartbeat', 'select();
if ($timeoutDevices) {
foreach ($timeoutDevices as $dev) {
Db::name('alarm_log')->insert([
'device_id' => $dev['id'],
'type' => 'heartbeat_timeout',
'created_at'=> date('Y-m-d H:i:s'),
]);
}
$output->writeln('发现 ' . count($timeoutDevices) . ' 台超时设备,已写入告警日志');
} else {
$output->writeln('暂无超时设备');
}
}
}
注意:确保数据库配置正确,且 runtime 目录有写权限,否则日志或插入可能失败。
注册命令并本地测试
编辑 application/command.php,添加该类完整命名空间:
<?php return [
'app\command\CheckDeviceHeartbeat',
];
然后在项目根目录运行验证:
-
php think list查看是否出现cron:check-device -
php think cron:check-device手动执行一次,观察输出和数据库变化
用 crontab 实现定时触发
Linux 下编辑定时任务:crontab -e,添加一行(每2分钟执行):
*/2 * * * * /usr/bin/php /var/www/your-project/think cron:check-device >> /var/log/device-check.log 2>&1
要点:
-
/usr/bin/php要换成你服务器上真实的 PHP 路径(可用which php查) -
/var/www/your-project/think是项目根目录下的入口文件,确保可执行 -
>> /var/log/...用于记录执行日志,便于排查问题
不复杂但容易忽略
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











