scheduler.py
2.45 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import schedule
import time
import os
from app.core.config import get_config, get_env, get_project_root
from app.core.db import get_connection, init_fts5_carbrands
from app.core.log import setup_logging
from app.brand_sync.fetcher import fetch_brands_from_mysql
from app.brand_sync.syncer import sync_brands
logger = setup_logging('sync_brand')
def sync_task():
config = get_config()
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)
# 从 .env 读取 MySQL 连接信息
mysql_host = get_env("MYSQL_HOST", "localhost")
mysql_port = int(get_env("MYSQL_PORT", "3306"))
mysql_user = get_env("MYSQL_USER", "root")
mysql_password = get_env("MYSQL_PASSWORD", "")
mysql_database = get_env("MYSQL_DATABASE", "cyb_os")
mysql_charset = get_env("MYSQL_CHARSET", "utf8mb4")
# 从 MySQL 获取品牌数据
brand_rows = fetch_brands_from_mysql(
host=mysql_host,
port=mysql_port,
user=mysql_user,
password=mysql_password,
database=mysql_database,
charset=mysql_charset,
)
if not brand_rows:
logger.warning("未获取到品牌数据,跳过本次同步。")
return
# 写入 SQLite
conn = get_connection(db_path)
try:
init_fts5_carbrands(conn)
sync_brands(conn, brand_rows)
except Exception as e:
logger.error(f"品牌同步过程中发生错误: {e}")
finally:
conn.close()
def run():
config = get_config()
schedule_day = config.get("brand_sync", "schedule_day", fallback="monday")
schedule_time = config.get("brand_sync", "schedule_time", fallback="03:00")
check_interval = config.getint("brand_sync", "check_interval", fallback=60)
sync_task()
# 定时调度
schedule_day_method = getattr(schedule.every(), schedule_day, None)
if schedule_day_method:
schedule_day_method.at(schedule_time).do(sync_task)
logger.info(f"品牌同步定时任务已启动,每{schedule_day} {schedule_time}执行。按 Ctrl+C 停止。")
else:
logger.warning(f"无效的调度日期: {schedule_day},仅执行一次启动同步。")
while True:
schedule.run_pending()
time.sleep(check_interval)