"""随应用生命周期运行的金币缓存定时检查,无需外部请求触发。""" import asyncio import logging from api.utils import official_gold, thirdpart_gold logger = logging.getLogger('dcalc.gold_refresh') CHECK_INTERVAL_SECONDS = 60 _periodic_tasks: list[asyncio.Task] = [] async def refresh_realtime(): async with thirdpart_gold.create_redis() as redis: data = await thirdpart_gold.read_cache(redis) await thirdpart_gold.schedule_refresh(redis, None, data) async def refresh_official(): async with thirdpart_gold.create_redis() as redis: await official_gold.refresh_cache(redis) async def _periodic(job): while True: try: await job() except Exception: logger.exception('periodic gold refresh check failed job=%s', job.__name__) await asyncio.sleep(CHECK_INTERVAL_SECONDS) async def start_periodic_refresh(): if _periodic_tasks: return for job in (refresh_realtime, refresh_official): _periodic_tasks.append(asyncio.create_task(_periodic(job), name=f'gold-periodic-{job.__name__}')) async def stop_periodic_refresh(): tasks = list(_periodic_tasks) for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) _periodic_tasks.clear()