使用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";
相关推荐
zzzsde1 分钟前
【Linux】文件:基础IO
linux·运维·服务器
qq_254674413 分钟前
Docker Docker Compose
运维·docker·容器
Aurora(^*_*^)5 分钟前
docker 部署openclaw踩坑记录
运维·docker·容器
wanhengidc15 分钟前
服务器托管对企业的作用
大数据·运维·服务器·分布式·智能手机
千百元21 分钟前
网络图标显示不正常
开发语言·网络·php
Yupureki35 分钟前
《Linux系统编程》15.进程间通信-管道
linux·运维·服务器·c语言·c++
Yupureki40 分钟前
《Linux系统编程》14.库的制作与原理
linux·运维·服务器·c语言·开发语言·c++
正点原子44 分钟前
瑞芯微工业级芯加持,正点原子RK3562J开发板/核心板解锁嵌入式开发新可能!
linux·ubuntu·嵌入式
hans汉斯1 小时前
基于污点分析的PHP应用威胁检测平台
开发语言·人工智能·算法·yolo·目标检测·php·无人机
路溪非溪1 小时前
Linux下wifi子系统的数据流
linux·arm开发·驱动开发