import argparse import logging import sys from apscheduler.schedulers.blocking import BlockingScheduler import config from db import Database from sync import SyncService from wechat import WeChatClient logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(description="UpdateDB - sync WeChat materials to database") parser.add_argument("--once", action="store_true", help="Run sync once and exit") args = parser.parse_args() logger.info("UpdateDB starting (sync interval: %dh)", config.SYNC_INTERVAL_HOURS) db = Database() wechat = WeChatClient() sync = SyncService(wechat, db) try: db.ensure_tables() # Run once at startup sync.run_sync() if args.once: logger.info("--once flag set, exiting after first sync") return scheduler = BlockingScheduler() scheduler.add_job( sync.run_sync, "interval", hours=config.SYNC_INTERVAL_HOURS, id="sync_job", max_instances=1, ) logger.info("Scheduler started, next sync in %d hours", config.SYNC_INTERVAL_HOURS) scheduler.start() except KeyboardInterrupt: logger.info("Shutting down") except Exception as e: logger.error("Fatal error: %s", e, exc_info=True) sys.exit(1) finally: wechat.close() db.close() if __name__ == "__main__": main()