使用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";
相关推荐
暴力求解1 分钟前
Linux---线程基础
linux·运维·服务器
JAVA面经实录91711 分钟前
计算机基础(完整版·超详细可背诵)
java·linux·数据结构·算法
晚风_END16 分钟前
Linux|操作系统|最新版openzfs编译记录
linux·运维·服务器·数据库·spring·中间件·个人开发
GanGanGanGan_22 分钟前
Rocky Linux 9 + XFCE 编译安装 fcitx5 + Rime 教程
linux·centos
咖喱o1 小时前
QinQ/VLAN Stacking
linux·运维·服务器·网络
xiaoye-duck1 小时前
《Linux系统编程》Linux指令 (二):从零开始理解Linux基础指令
linux
FYKJ_20101 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
月白风清江有声1 小时前
安装mingw 版 cmake
linux
sduwcgg2 小时前
IQ-Learn 在 RTX 3090 服务器上的环境配置与踩坑记录
运维·服务器
呱呱巨基2 小时前
Linux 基础IO
linux·c++·笔记·学习