使用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";
相关推荐
yaoxin52112330 分钟前
第十二章 I 开头的术语
运维·服务器
ProgramHan31 分钟前
1992-2025年中国计算机发展状况:服务器、电脑端与移动端的演进
运维·服务器·电脑
马立杰4 小时前
H3CNE-33-BGP
运维·网络·h3cne
字节全栈_rJF4 小时前
概述、 BGP AS 、BGP 邻居、 BGP 更新源 、BGP TTL 、BGP路由表、 BGP 同步
网络·智能路由器·php
云空5 小时前
《DeepSeek 网页/API 性能异常(DeepSeek Web/API Degraded Performance):网络安全日志》
运维·人工智能·web安全·网络安全·开源·网络攻击模型·安全威胁分析
深度Linux5 小时前
Linux网络编程中的零拷贝:提升性能的秘密武器
linux·linux内核·零拷贝技术
没有名字的小羊6 小时前
Cyber Security 101-Build Your Cyber Security Career-Security Principles(安全原则)
运维·网络·安全
千夜啊6 小时前
Nginx 运维开发高频面试题详解
运维·nginx·运维开发
dal118网工任子仪6 小时前
92,[8] 攻防世界 web Web_php_wrong_nginx_config
开发语言·php
存储服务专家StorageExpert7 小时前
答疑解惑:如何监控EMC unity存储系统磁盘重构rebuild进度
运维·unity·存储维护·emc存储