使用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";
相关推荐
linchare2 小时前
linux debian上只装mysql的客户端步骤
linux·mysql·debian
wanhengidc3 小时前
网站服务器都有哪些作用?
运维·服务器·科技·智能手机·云计算
百***75744 小时前
linux上redis升级
linux·运维·redis
顾安r4 小时前
11.22 脚本打包APP 排错指南
linux·服务器·开发语言·前端·flask
Neur0toxin4 小时前
入侵排查_2025/11/23
linux·windows·应急响应
小小编程能手5 小时前
Linux文件编程
linux·运维·服务器
木童6625 小时前
nginx安装步骤详解
linux·运维·服务器·网络·nginx
暴躁的菜鸡6 小时前
Ubuntu安装向日葵
linux·运维·ubuntu
4***V2026 小时前
PHP在微服务通信中的消息队列
开发语言·微服务·php
wa的一声哭了6 小时前
Webase部署Webase-Web在合约IDE页面一直转圈
linux·运维·服务器·前端·python·区块链·ssh