scheduler.py
1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import schedule
import time
from app.core.config import get_config
from app.core.db import get_connection, init_fts5_merchants
from app.core.log import setup_logging
from app.sync.fetcher import fetch_merchants
from app.sync.syncer import sync_merchants
from app.core.config import get_project_root
import os
logger = setup_logging('sync_data')
def sync_task():
config = get_config()
api_url = config.get("api", "data_url", fallback="")
item_codes = config.get("api", "item_codes", fallback="")
days_range = config.getint("sync", "data_range_days", fallback=30)
db_path = config.get("db", "db_path", fallback="data/merchants_fts.db")
if not os.path.isabs(db_path):
db_path = os.path.join(get_project_root(), db_path)
logger.info("开始执行同步任务...")
data_dir = os.path.dirname(db_path)
if not os.path.exists(data_dir):
os.makedirs(data_dir)
api_rows = fetch_merchants(api_url, item_codes, days_range)
if not api_rows:
logger.warning("未获取到有效数据,跳过本次同步。")
return
conn = get_connection(db_path)
try:
init_fts5_merchants(conn)
sync_merchants(conn, api_rows)
except Exception as e:
logger.error(f"同步过程中发生错误: {e}")
finally:
conn.close()
def run():
config = get_config()
interval_hours = config.getint("sync", "interval_hours", fallback=12)
check_interval = config.getint("sync", "check_interval", fallback=60)
sync_task()
schedule.every(interval_hours).hours.do(sync_task)
logger.info(f"定时任务已启动,每 {interval_hours} 小时同步一次。按 Ctrl+C 停止。")
while True:
schedule.run_pending()
time.sleep(check_interval)