使用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";
相关推荐
KYGALYX2 小时前
在Linux中备份msyql数据库和表的详细操作
linux·运维·数据库
余—笙3 小时前
Linux(docker)安装搭建CuteHttpFileServer/chfs文件共享服务器
linux·服务器·docker
lang201509283 小时前
Linux高效备份:tar与gzip完全指南
linux·运维·服务器
IDOlaoluo3 小时前
OceanBase all-in-one 4.2.0.0 安装教程(CentOS 7/EL7 一键部署详细步骤)
linux·centos·oceanbase
kali-Myon3 小时前
NewStarCTF2025-Week4-Web
sql·安全·web安全·php·ctf·ssti·ssrf
wanhengidc3 小时前
云手机的基本原理
运维·服务器·游戏·智能手机·云计算
篙芷4 小时前
两台服务器 NFS 共享目录实战
运维·服务器
catoop4 小时前
在 WSL 的 Ubuntu 中安装和配置 SSH 服务
linux·ubuntu·ssh
Hard but lovely4 小时前
linux: centos 软件包管理 yum源
linux·运维·centos
悲伤小伞4 小时前
Linux_Socket_UDP
linux·服务器·网络·c++·网络协议·udp