|
"""
|
|
定时任务模块 - 定期更新所有API密钥
|
|
"""
|
|
import json
|
|
import os
|
|
import time
|
|
import sched
|
|
import threading
|
|
import sqlite3
|
|
from core.update import update
|
|
from utils.db import get_db_connection
|
|
from config import API_KEYS_FILE
|
|
|
|
|
|
UPDATE_INTERVAL = 12 * 60 * 60
|
|
|
|
def update_all_keys():
|
|
"""
|
|
更新所有API密钥
|
|
"""
|
|
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 开始更新所有API密钥...")
|
|
|
|
|
|
conn = get_db_connection()
|
|
key_ids = []
|
|
|
|
try:
|
|
cursor = conn.cursor()
|
|
cursor.execute('SELECT id FROM api_keys')
|
|
rows = cursor.fetchall()
|
|
key_ids = [row['id'] for row in rows]
|
|
except sqlite3.Error as e:
|
|
print(f"从数据库获取密钥时出错: {str(e)}")
|
|
|
|
|
|
if os.path.exists(API_KEYS_FILE):
|
|
try:
|
|
with open(API_KEYS_FILE, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
key_ids = [key["id"] for key in data.get("api_keys", [])]
|
|
except Exception as e:
|
|
print(f"读取API密钥文件失败: {str(e)}")
|
|
return
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
|
|
|
|
if not key_ids:
|
|
print("没有找到API密钥,跳过更新")
|
|
return
|
|
|
|
|
|
for key_id in key_ids:
|
|
result = update(key_id)
|
|
if result["success"]:
|
|
print(f" - 密钥 {key_id} 更新成功")
|
|
else:
|
|
print(f" - 密钥 {key_id} 更新失败: {result['message']}")
|
|
|
|
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 完成所有API密钥更新")
|
|
|
|
def run_scheduler():
|
|
"""
|
|
运行定时任务
|
|
"""
|
|
scheduler = sched.scheduler(time.time, time.sleep)
|
|
|
|
def scheduled_update():
|
|
update_all_keys()
|
|
|
|
scheduler.enter(UPDATE_INTERVAL, 1, scheduled_update, ())
|
|
|
|
|
|
scheduler.enter(UPDATE_INTERVAL, 1, scheduled_update, ())
|
|
|
|
print(f"定时任务已启动,每 {UPDATE_INTERVAL // 3600} 小时更新一次API密钥")
|
|
scheduler.run()
|
|
|
|
if __name__ == "__main__":
|
|
|
|
scheduler_thread = threading.Thread(target=run_scheduler)
|
|
scheduler_thread.daemon = True
|
|
scheduler_thread.start()
|
|
|
|
|
|
while True:
|
|
time.sleep(60)
|
|
|