60 lines
2.2 KiB
Python
60 lines
2.2 KiB
Python
"""高股息独立调度入口;不占每日计划及五分钟修订的运行锁。"""
|
||
import datetime as dt
|
||
import threading
|
||
import uuid
|
||
|
||
from fastapi import APIRouter, Header, HTTPException, Query
|
||
from xxl import _require_key, _run_step, _notify
|
||
|
||
router = APIRouter(prefix='/api/v1/xxl', tags=['dividend-research'])
|
||
_lock = threading.Lock()
|
||
_jobs = {}
|
||
_running = None
|
||
|
||
|
||
def _run(job_id, callback):
|
||
global _running
|
||
job = _jobs[job_id]
|
||
ok = False
|
||
note = ''
|
||
try:
|
||
rc, output = _run_step(['dividend_watch.py', 'scan'])
|
||
ok = rc == 0
|
||
note = output[-2000:]
|
||
except Exception as exc:
|
||
note = type(exc).__name__
|
||
finally:
|
||
with _lock:
|
||
job.update(state='success' if ok else 'failed', note=note,
|
||
ended_at=dt.datetime.now(dt.timezone.utc).isoformat())
|
||
_running = None
|
||
_notify(job, callback, ok, note)
|
||
job['closed'] = True
|
||
|
||
|
||
@router.api_route('/dividend-watch', methods=['GET', 'POST'])
|
||
def trigger(callbackUrl: str = Query(None), key: str = Query(None), x_job_key: str = Header(None)):
|
||
"""交易日08:05,只读采集并写独立研究文件。使用既有XXL鉴权与回调。"""
|
||
global _running
|
||
_require_key(x_job_key, key)
|
||
with _lock:
|
||
if _running:
|
||
raise HTTPException(status_code=409, detail='高股息检查已在运行')
|
||
identity = str(uuid.uuid4())
|
||
_jobs[identity] = {'task_id': identity, 'state': 'running', 'closed': False,
|
||
'started_at': dt.datetime.now(dt.timezone.utc).isoformat(), 'tail': []}
|
||
_running = identity
|
||
for old in list(_jobs):
|
||
if len(_jobs) > 20 and _jobs[old].get('closed'):
|
||
del _jobs[old]
|
||
threading.Thread(target=_run, args=(identity, callbackUrl), daemon=True).start()
|
||
return {'status': 'accepted', 'task_id': identity}
|
||
|
||
|
||
@router.get('/dividend-watch/status/{task_id}')
|
||
def status(task_id: str, key: str = Query(None), x_job_key: str = Header(None)):
|
||
_require_key(x_job_key, key)
|
||
if task_id not in _jobs:
|
||
raise HTTPException(status_code=404, detail='任务记录不可用,请查研究日检;不可推断成功')
|
||
return _jobs[task_id]
|