- services/cache.py 新增 clear_all() 清空整个 cache 表 - daily_collector.py 新增 cache_cleanup_loop() 后台循环:精确 sleep 到最近一个 工作日 9:31 清空缓存,跳过周末,出错1分钟重试 - main.py lifespan 启动清理任务,与采集任务一同优雅退出 与既有"非交易时段 TTL 截止到下次开盘前"的惰性过期形成双保险 Co-Authored-By: Claude <noreply@anthropic.com>
69 lines
1.8 KiB
Python
69 lines
1.8 KiB
Python
"""磁盘缓存:SQLite 持久化,重启不丢"""
|
||
|
||
import json
|
||
from datetime import datetime, timedelta
|
||
from typing import Optional
|
||
|
||
from database import get_connection
|
||
|
||
|
||
def get_cache(key: str) -> Optional[str]:
|
||
"""获取缓存,过期或不存在返回 None"""
|
||
now = datetime.now().isoformat()
|
||
conn = get_connection()
|
||
try:
|
||
row = conn.execute(
|
||
"SELECT value FROM cache WHERE key = ? AND expires_at > ?",
|
||
(key, now),
|
||
).fetchone()
|
||
if row:
|
||
return row["value"]
|
||
return None
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def set_cache(key: str, value: str, ttl_hours: int = 6, ttl_seconds: int = 0):
|
||
"""写入缓存,过期时间 = now + ttl_hours + ttl_seconds(支持秒级短 TTL)"""
|
||
expires_at = (datetime.now() + timedelta(hours=ttl_hours, seconds=ttl_seconds)).isoformat()
|
||
conn = get_connection()
|
||
try:
|
||
conn.execute(
|
||
"INSERT OR REPLACE INTO cache (key, value, expires_at) VALUES (?, ?, ?)",
|
||
(key, value, expires_at),
|
||
)
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def del_cache(key: str):
|
||
"""删除指定缓存"""
|
||
conn = get_connection()
|
||
try:
|
||
conn.execute("DELETE FROM cache WHERE key = ?", (key,))
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def clean_expired():
|
||
"""清理已过期的缓存(可在启动时调用一次)"""
|
||
now = datetime.now().isoformat()
|
||
conn = get_connection()
|
||
try:
|
||
conn.execute("DELETE FROM cache WHERE expires_at <= ?", (now,))
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def clear_all():
|
||
"""清空全部缓存(每日开盘后 9:31 调用,保证当日数据全新)"""
|
||
conn = get_connection()
|
||
try:
|
||
conn.execute("DELETE FROM cache")
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|