QaQlinks / Python实例 / 3_run_flush_aplus_image_urls.py 131 个条目

3_run_flush_aplus_image_urls.py

Python实例 #642 更新 2026-08-14

定时清理脚本:到点删掉 A+ 图片表里不是当天的旧记录,保持表体积可控。TARGET_TIME 可以改成任意时刻,配合前两步循环执行,就能一直维持「当天数据」的干净状态。



import pymysql
from datetime import datetime, timedelta
import time
# 数据库配置
db_config = {
    'host': '',
    'user': '',
    'password': '',
    'database': ''
}
# 设置每天执行的时间节点 (24小时制)
TARGET_TIME = "00:00"  # 可更改为其他时间节点,例如 "02:30"
def delete_old_entries():
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            # 获取今天的日期
            today = datetime.now().date()
            # SQL查询语句:删除asin相同且日期不是今天的行
            sql = """
            DELETE FROM aplus_urls
            WHERE asin IS NOT NULL 
              AND date < %s 
              AND id NOT IN (
                  SELECT id FROM (
                      SELECT id
                      FROM aplus_urls
                      WHERE date = %s
                  ) AS temp
              );
            """
            cursor.execute(sql, (today, today))
            connection.commit()
            print(f"Deleted old entries for date {today} at {datetime.now()}.")
    except Exception as e:
        print("Error occurred:", e)
    finally:
        connection.close()
def run_daily():
    while True:
        # 获取当前时间
        now = datetime.now()
        # 解析目标时间
        target_hour, target_minute = map(int, TARGET_TIME.split(':'))
        target_time = now.replace(hour=9, minute=43, second=0, microsecond=0)
        # 如果当前时间已经过了目标时间,则设置下一个执行时间为明天的目标时间
        if now >= target_time:
            target_time += timedelta(days=1)
        # 计算距离下一个目标时间的秒数
        wait_time = (target_time - now).total_seconds()
        # 打印等待时间,方便调试
        print(f"Waiting for {wait_time} seconds until {TARGET_TIME} to run.")
        # 等待到下一个目标时间
        time.sleep(wait_time)
        # 到达目标时间时执行删除操作
        delete_old_entries()
if __name__ == "__main__":
    run_daily()


点击统计

最近 30 天 · 单日最高 9 · 数据刚开始累积
9总点击
0今日
9近 7 天
0.3日均
03691211-26 · 9 次10-2911-0511-1311-20今天

记录信息

分类
Python实例
类型
Python 脚本
使用
完整说明在原站详情页,可以前往查看
更新
2026-08-14
点击
9 次
编号
#642