Delete cron.py
Browse files
cron.py
DELETED
@@ -1,88 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
定时任务模块 - 定期更新所有API密钥
|
3 |
-
"""
|
4 |
-
import json
|
5 |
-
import os
|
6 |
-
import time
|
7 |
-
import sched
|
8 |
-
import threading
|
9 |
-
import sqlite3
|
10 |
-
from update import update
|
11 |
-
from utils.db import get_db_connection
|
12 |
-
from config import API_KEYS_FILE
|
13 |
-
|
14 |
-
# 定义更新间隔(12小时,单位:秒)
|
15 |
-
UPDATE_INTERVAL = 12 * 60 * 60
|
16 |
-
|
17 |
-
def update_all_keys():
|
18 |
-
"""
|
19 |
-
更新所有API密钥
|
20 |
-
"""
|
21 |
-
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 开始更新所有API密钥...")
|
22 |
-
|
23 |
-
# 从SQLite数据库获取所有密钥ID
|
24 |
-
conn = get_db_connection()
|
25 |
-
key_ids = []
|
26 |
-
|
27 |
-
try:
|
28 |
-
cursor = conn.cursor()
|
29 |
-
cursor.execute('SELECT id FROM api_keys')
|
30 |
-
rows = cursor.fetchall()
|
31 |
-
key_ids = [row['id'] for row in rows]
|
32 |
-
except sqlite3.Error as e:
|
33 |
-
print(f"从数据库获取密钥时出错: {str(e)}")
|
34 |
-
|
35 |
-
# 备用方案:尝试从JSON文件读取
|
36 |
-
if os.path.exists(API_KEYS_FILE):
|
37 |
-
try:
|
38 |
-
with open(API_KEYS_FILE, "r", encoding="utf-8") as f:
|
39 |
-
data = json.load(f)
|
40 |
-
key_ids = [key["id"] for key in data.get("api_keys", [])]
|
41 |
-
except Exception as e:
|
42 |
-
print(f"读取API密钥文件失败: {str(e)}")
|
43 |
-
return
|
44 |
-
finally:
|
45 |
-
if conn:
|
46 |
-
conn.close()
|
47 |
-
|
48 |
-
# 如果没有找到密钥,则退出
|
49 |
-
if not key_ids:
|
50 |
-
print("没有找到API密钥,跳过更新")
|
51 |
-
return
|
52 |
-
|
53 |
-
# 逐个更新API密钥
|
54 |
-
for key_id in key_ids:
|
55 |
-
result = update(key_id)
|
56 |
-
if result["success"]:
|
57 |
-
print(f" - 密钥 {key_id} 更新成功")
|
58 |
-
else:
|
59 |
-
print(f" - 密钥 {key_id} 更新失败: {result['message']}")
|
60 |
-
|
61 |
-
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 完成所有API密钥更新")
|
62 |
-
|
63 |
-
def run_scheduler():
|
64 |
-
"""
|
65 |
-
运行定时任务
|
66 |
-
"""
|
67 |
-
scheduler = sched.scheduler(time.time, time.sleep)
|
68 |
-
|
69 |
-
def scheduled_update():
|
70 |
-
update_all_keys()
|
71 |
-
# 再次安排下一次更新
|
72 |
-
scheduler.enter(UPDATE_INTERVAL, 1, scheduled_update, ())
|
73 |
-
|
74 |
-
# 首次安排更新
|
75 |
-
scheduler.enter(UPDATE_INTERVAL, 1, scheduled_update, ())
|
76 |
-
|
77 |
-
print(f"定时任务已启动,每 {UPDATE_INTERVAL // 3600} 小时更新一次API密钥")
|
78 |
-
scheduler.run()
|
79 |
-
|
80 |
-
if __name__ == "__main__":
|
81 |
-
# 在单独的线程中运行定时任务,避免阻塞主线程
|
82 |
-
scheduler_thread = threading.Thread(target=run_scheduler)
|
83 |
-
scheduler_thread.daemon = True # 设置为守护线程,当主线程退出时自动结束
|
84 |
-
scheduler_thread.start()
|
85 |
-
|
86 |
-
# 保持主线程运行(可选,根据实际需求)
|
87 |
-
while True:
|
88 |
-
time.sleep(60)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|