使用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";
相关推荐
鹿角片ljp12 小时前
实验室显卡与本机远程连接复盘:直连SSH到ZeroTier
运维·ssh
sbjdhjd12 小时前
企业级 Docker 镜像仓库建设与运维规范
linux·运维·docker·云原生·容器·eureka·开源
TEC_INO12 小时前
Linux_54:RV1126的VI模块讲解
linux·运维·人工智能
kdxiaojie12 小时前
U-Boot分析【学习笔记】(6)
linux·笔记·学习
期待のcode12 小时前
Redis数据类型
运维·数据结构·redis
Tingjct12 小时前
Linux开发工具
linux·运维·服务器
cui_ruicheng13 小时前
Linux线程(三):线程同步、互斥与生产者消费者模型
linux·服务器·开发语言
xingyuzhisuan13 小时前
适合微调Llama 3 70B模型的最低GPU配置推荐
运维·人工智能·算法·llama·gpu算力
Harvy_没救了13 小时前
【网络运维】从开发到上线全流程简化方案
运维·网络
信看13 小时前
CM4 网口排查步骤
linux