智慧教务系统
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

103 lines
3.7 KiB

<?php
// +----------------------------------------------------------------------
// | Niucloud-admin 企业快速开发的多应用管理平台
// +----------------------------------------------------------------------
// | 官方网址:https://www.niucloud.com
// +----------------------------------------------------------------------
// | niucloud团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: Niucloud Team
// +----------------------------------------------------------------------
namespace app\job\schedule;
use app\model\course_schedule\CourseSchedule;
use core\base\BaseJob;
use think\facade\Db;
use think\facade\Log;
/**
* 队列异步调用定时任务
*/
class HandleCourseSchedule extends BaseJob
{
public function doJob()
{
// 添加执行锁,防止重复执行
$lockFile = runtime_path() . 'course_status_update.lock';
if (file_exists($lockFile) && (time() - filemtime($lockFile)) < 300) { // 5分钟锁定
Log::write('课程状态更新任务正在执行中,跳过');
return ['status' => 'skipped', 'reason' => 'locked'];
}
// 创建锁文件
file_put_contents($lockFile, time());
try {
Log::write('课程状态自动化任务开始' . date('Y-m-d H:i:s'));
$result = $this->handleCourseStatus();
Log::write('课程状态自动化任务完成' . date('Y-m-d H:i:s'));
return $result;
} finally {
// 删除锁文件
if (file_exists($lockFile)) {
unlink($lockFile);
}
}
}
private function handleCourseStatus()
{
try {
Db::startTrans();
// 批量更新,避免循环操作
$yesterday = date('Y-m-d', strtotime('-1 day'));
// 先查询需要更新的记录数量
$totalCount = CourseSchedule::where('course_date', '<', date('Y-m-d'))
->where('status', '<>', 'completed') // 避免重复更新已完成的课程
->count();
if ($totalCount == 0) {
Log::write('没有需要更新状态的过期课程');
Db::commit();
return [
'status' => 'success',
'total_count' => 0,
'updated_count' => 0,
'message' => '没有需要更新状态的过期课程'
];
}
// 批量更新过期课程状态
$affectedRows = CourseSchedule::where('course_date', '<', date('Y-m-d'))
->where('status', '<>', 'completed') // 避免重复更新
->update([
'status' => 'completed',
'updated_at' => time()
]);
Log::write('批量更新了' . $affectedRows . '个过期课程状态为已完成,总共检查了' . $totalCount . '个课程');
Db::commit();
return [
'status' => 'success',
'total_count' => $totalCount,
'updated_count' => $affectedRows,
'message' => '成功更新' . $affectedRows . '个过期课程状态'
];
} catch (\Exception $e) {
Db::rollback();
Log::write('更新课程状态失败:' . $e->getMessage());
return [
'status' => 'failed',
'total_count' => 0,
'updated_count' => 0,
'error' => $e->getMessage()
];
}
}
}