crontab -e 编辑定时任务 crontab -l 查看定时任务,select-editor 选择编辑器
0 0 * * * /usr/bin/php /www/wwwroot/www.jingzhunshuju.com/check_and_delete_students.php
check_and_delete_students.php内代码:
php
<?php
//php脚本,定时运行,http://whzc.self/check_and_delete_students.php
class StudentManager
{
private $pdo;
public function __construct($dsn, $username, $password)
{
try {
$this->pdo = new PDO($dsn, $username, $password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Could not connect to the database: " . $e->getMessage());
}
}
public function deleteExpiredStudents($days = 7)
{
// 计算过期时间戳
$currentTime = time();
$expireTime = $currentTime - ($days * 24 * 3600);
// 准备SQL语句
$sql = "UPDATE yucheng_students
SET is_del = :deleted
WHERE students_createtime < :expireTime
AND students_checkstate IN (:pending, :failed)";
// 准备参数
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':deleted', '删除', PDO::PARAM_STR);
$stmt->bindValue(':expireTime', $expireTime, PDO::PARAM_INT);
$stmt->bindValue(':pending', '正在审核', PDO::PARAM_STR);
$stmt->bindValue(':failed', '不通过', PDO::PARAM_STR);
// 执行SQL语句
$affectedRows = $stmt->execute();
return $affectedRows; // 返回受影响的行数
}
}
// 使用示例
$dsn = 'mysql:host=localhost;dbname=yucheng1272423856;charset=utf8';
$username = 'root';
$password = 'ghjjjbbjk900~~';
$studentManager = new StudentManager($dsn, $username, $password);
$deletedCount = $studentManager->deleteExpiredStudents(7);
echo "Deleted {$deletedCount} expired students.\n";