使用Linux之crontab -e创建定时任务,每天执行一次php脚本,清除7天没有审核通过的数据库记录

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";
相关推荐
kymjs张涛10 小时前
OpenClaw 学习小组:初识
android·linux·人工智能
程序设计实验室12 小时前
经历分享,发现挖矿木马后,服务器快速备份与重装(腾讯云平台)
linux
ServBay12 小时前
告别面条代码,PSL 5.0 重构 PHP 性能与安全天花板
后端·php
Miku1613 小时前
OpenClaw-Linux+飞书官方Plugin安装指南
linux·人工智能·agent
Miku1613 小时前
OpenClaw 接入 QQ Bot 完整实践指南
linux·人工智能·agent
Yogurt_cry18 小时前
[树莓派4B] 闲置近10年的爱普生 L310 打印机爆改无线打印机
linux·物联网·树莓派
爱吃橘子橙子柚子2 天前
3CPU性能排查总结(超详细)【Linux性能优化】
运维·cpu
Johny_Zhao2 天前
OpenClaw中级到高级教程
linux·人工智能·信息安全·kubernetes·云计算·yum源·系统运维·openclaw
Sheffield2 天前
Docker的跨主机服务与其对应的优缺点
linux·网络协议·docker
Sheffield3 天前
Alpine是什么,为什么是Docker首选?
linux·docker·容器