3_run_flush_aplus_image_urls.py
定时清理脚本:到点删掉 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()