# -*- coding: utf-8 -*- """AI 定时任务调度器:到点后自动执行一次用户委托的 AI 指令。 - 用户在对话中通过 create_scheduled_task 工具创建任务,三种时间模式: 绝对时间(scheduled_at)/ 计时器(delay_minutes,从现在往后计时)/ 重复任务(repeat_minutes 间隔,可选 repeat_until 截止,到期自动结束)。 - 后台线程每 10 秒轮询认领到点任务,线程池内跑一次完整 agent loop: 写操作自动视为用户已确认(创建任务即明确委托)。 - 重复任务每次执行后按锚点推进下一次并写回会话报告,用户取消为止; 服务停机错过的时间段自动跳过,不补跑。 - 体验优先:执行不受每日 token 限额拦截(超限也让任务跑完自然结束),到任务结束 后限额继续生效;token 用量照常入账供管理端查看。 - 执行结果写回用户会话,用户打开 AI 对话即可看到代理执行报告。 - 服务器停机导致错过的任务:24 小时内补跑,超过的直接标记失败不再执行。 """ import time import threading from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timedelta from flask import current_app from app.models import db, User, AiConversation, AiConversationMessage, AiScheduledTask from app.time_utils import BJ_TZ POLL_INTERVAL_SECONDS = 10 MAX_WORKERS = 3 # 认领后超过该时长仍未结束视为执行中断(服务重启等),标记失败 STALE_RUNNING_HOURS = 1 # 错过计划时间超过该时长的任务不再补跑 STALE_DUE_HOURS = 24 MIN_LEAD_SECONDS = 60 MAX_HORIZON_DAYS = 90 MAX_INSTRUCTION_CHARS = 2000 MAX_REPEAT_RUNS = 1000 # 单个重复任务执行次数上限(安全阀) # 定时任务执行时注入的无人值守策略:到点即选课窗口,AI 实时查课自主决策。 # 核心是防犹豫:多个候选全部创建抢课任务,先到先得,抢到多个由用户自行取舍。 EXECUTION_POLICY = """【无人值守执行策略】你正在执行用户预先委托的定时任务,用户不在线:所有写操作自动视为已确认,不要请求确认,也不要调用 ask_user 提问(无人回答),一切依据任务指令自主决策。 - 本次要选的是“下学期可选课程”,务必用 search_live_courses 实时查询获取可选课程与教学班 ID;课程索引缓存的是当学期已有课程,与本次选课无关,禁止用它推定。 - 严禁犹豫不决:符合用户目标的课程或教学班若有多个候选,全部逐一创建抢课任务(先到先得,抢到多个由用户自行取舍),不要挑选,也不要只创建其中一个。 - 实时查询不可用或查不到目标课程时,如实说明原因结束任务,不要编造课程或 ID。 - 结束时输出简洁报告:创建了哪些抢课任务(课程/教师/任务ID/状态)、哪些没成及原因。""" _app = None _pool = None _started = threading.Event() def _naive_now() -> datetime: """当前北京时间(naive,与库内 created_at / scheduled_time 的存储约定一致)。""" return datetime.now(BJ_TZ).replace(tzinfo=None) def _parse_bj_datetime(text) -> datetime: """解析北京时间(naive);带时区的 ISO 串自动换算。失败返回 None。""" text = str(text or '').strip() if not text: return None try: parsed = datetime.fromisoformat(text.replace('Z', '+00:00').replace(' ', 'T', 1)) if parsed.tzinfo is not None: parsed = parsed.astimezone(BJ_TZ).replace(tzinfo=None) return parsed except ValueError: pass for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y/%m/%d %H:%M', '%Y-%m-%d'): try: return datetime.strptime(text, fmt) except ValueError: continue return None def _next_occurrence(task, now) -> datetime: """重复任务的下一次执行时间:锚定 scheduled_at 推进,跳过错过的时段。""" next_at = task.scheduled_at step = timedelta(seconds=max(int(task.repeat_interval or 0), MIN_LEAD_SECONDS)) while next_at <= now: next_at += step return next_at def create_task(user_id: int, scheduled_at_raw, instruction, conversation_id=None, delay_minutes=None, repeat_minutes=None, repeat_until_raw=None) -> dict: """创建定时任务(含校验)。供 AI 工具与后续管理接口复用。 时间模式二选一:scheduled_at 绝对时间 / delay_minutes 计时器(从现在往后计时)。 repeat_minutes(分钟)可选:按间隔重复执行,repeat_until 可选截止时间。 """ instruction = str(instruction or '').strip() if not instruction: return {'success': False, 'message': '缺少任务指令'} now = _naive_now() # 首次执行时间:计时器与绝对时间二选一 if delay_minutes is not None and str(scheduled_at_raw or '').strip(): return {'success': False, 'message': 'delay_minutes 与 scheduled_at 只能二选一'} if delay_minutes is not None: try: delay = float(delay_minutes) except (TypeError, ValueError): return {'success': False, 'message': 'delay_minutes 必须是数字(分钟)'} if delay * 60 < MIN_LEAD_SECONDS: return {'success': False, 'message': '计时器至少 1 分钟'} if delay > MAX_HORIZON_DAYS * 1440: return {'success': False, 'message': f'计时器不能超过 {MAX_HORIZON_DAYS} 天'} scheduled_at = now + timedelta(minutes=delay) time_desc = f'{delay:g} 分钟后({scheduled_at:%Y-%m-%d %H:%M})' else: scheduled_at = _parse_bj_datetime(scheduled_at_raw) if scheduled_at is None: return {'success': False, 'message': '时间格式无法解析,请使用如 2026-09-15 08:00 的北京时间格式'} if scheduled_at < now + timedelta(seconds=MIN_LEAD_SECONDS): return {'success': False, 'message': '执行时间必须至少在 1 分钟之后'} if scheduled_at > now + timedelta(days=MAX_HORIZON_DAYS): return {'success': False, 'message': f'执行时间不能超过 {MAX_HORIZON_DAYS} 天之后'} time_desc = f'{scheduled_at:%Y-%m-%d %H:%M}' # 重复设置 repeat_interval = None repeat_until = None if repeat_minutes not in (None, ''): try: minutes = int(float(repeat_minutes)) except (TypeError, ValueError): return {'success': False, 'message': 'repeat_minutes 必须是数字(分钟)'} if minutes < 1: return {'success': False, 'message': '重复间隔至少 1 分钟'} if minutes > MAX_HORIZON_DAYS * 1440: return {'success': False, 'message': f'重复间隔不能超过 {MAX_HORIZON_DAYS} 天'} repeat_interval = minutes * 60 if str(repeat_until_raw or '').strip(): if repeat_interval is None: return {'success': False, 'message': 'repeat_until 需要配合 repeat_minutes 使用'} repeat_until = _parse_bj_datetime(repeat_until_raw) if repeat_until is None: return {'success': False, 'message': 'repeat_until 格式无法解析,请使用如 2026-09-15 08:00 的北京时间格式'} if repeat_until <= scheduled_at: return {'success': False, 'message': '重复截止时间必须晚于首次执行时间'} if repeat_until > now + timedelta(days=MAX_HORIZON_DAYS): return {'success': False, 'message': f'重复截止时间不能超过 {MAX_HORIZON_DAYS} 天之后'} task = AiScheduledTask( user_id=user_id, conversation_id=conversation_id, instruction=instruction[:MAX_INSTRUCTION_CHARS], scheduled_at=scheduled_at, repeat_interval=repeat_interval, repeat_until=repeat_until, ) db.session.add(task) db.session.commit() repeat_desc = '' if repeat_interval: repeat_desc = f',每 {repeat_interval // 60} 分钟重复一次' if repeat_until: repeat_desc += f',至 {repeat_until:%Y-%m-%d %H:%M} 自动结束' return { 'success': True, 'message': f'定时任务已创建,将于 {time_desc} 自动执行{repeat_desc}', 'task': task.to_dict(), } def cancel_own_task(user_id: int, task_id: int) -> dict: task = AiScheduledTask.query.filter_by(id=int(task_id or 0), user_id=user_id).first() if not task: return {'success': False, 'message': '任务不存在或无权取消'} if task.status != AiScheduledTask.STATUS_PENDING: return {'success': False, 'message': '任务已开始执行或已结束,无法取消'} task.status = AiScheduledTask.STATUS_CANCELLED db.session.commit() return {'success': True, 'message': '定时任务已取消', 'task': task.to_dict()} def init_scheduler(app) -> None: """启动调度线程与执行线程池(幂等,随 create_app 调用)。""" if _started.is_set(): return _started.set() global _app, _pool _app = app _pool = ThreadPoolExecutor(max_workers=MAX_WORKERS, thread_name_prefix='ai-sched') threading.Thread(target=_loop, args=(app,), daemon=True, name='ai-scheduler').start() print('[ai_scheduler] AI 定时任务调度器已启动') def _loop(app) -> None: while True: try: with app.app_context(): run_due_tasks() except Exception: app.logger.exception('AI 定时任务调度轮询失败') time.sleep(POLL_INTERVAL_SECONDS) def run_due_tasks(wait: bool = False) -> list: """认领所有到点任务并派发执行。返回本次派发的任务 id 列表。 wait=True 时阻塞到全部执行完成(冒烟测试用)。 """ now = _naive_now() # 恢复中断:认领后长时间未结束的任务(服务重启导致线程丢失) stale_before = now - timedelta(hours=STALE_RUNNING_HOURS) stuck = AiScheduledTask.query.filter( AiScheduledTask.status == AiScheduledTask.STATUS_RUNNING, AiScheduledTask.claimed_at < stale_before, ).all() for task in stuck: if task.repeat_interval: # 重复任务:中断的那次视为跳过,推进到下一次(到期则结束) next_at = _next_occurrence(task, now) if task.repeat_until and next_at > task.repeat_until: task.status = AiScheduledTask.STATUS_ENDED task.claimed_at = None task.error = '一次执行中断(服务重启或超时);重复计划已到期自动结束' else: task.scheduled_at = next_at task.status = AiScheduledTask.STATUS_PENDING task.claimed_at = None task.error = '一次执行中断(服务重启或超时),已跳到下一次' else: task.status = AiScheduledTask.STATUS_FAILED task.error = '执行中断(服务重启或超时),请重新创建任务' task.executed_at = now # 错过太久的不补跑 missed = AiScheduledTask.query.filter( AiScheduledTask.status == AiScheduledTask.STATUS_PENDING, AiScheduledTask.scheduled_at < now - timedelta(hours=STALE_DUE_HOURS), ).all() for task in missed: if task.repeat_interval: next_at = _next_occurrence(task, now) if task.repeat_until and next_at > task.repeat_until: task.status = AiScheduledTask.STATUS_ENDED task.error = '重复计划已到期自动结束' else: task.scheduled_at = next_at task.error = '错过若干次执行(服务器当时未运行),已跳到下一次' else: task.status = AiScheduledTask.STATUS_FAILED task.error = '错过执行时间(服务器当时未运行),已跳过' task.executed_at = now # 认领到点任务(单一线程轮询,先改状态再派发,天然防重复认领) due = AiScheduledTask.query.filter( AiScheduledTask.status == AiScheduledTask.STATUS_PENDING, AiScheduledTask.scheduled_at <= now, ).all() dispatched = [] for task in due: task.status = AiScheduledTask.STATUS_RUNNING task.claimed_at = now dispatched.append(task.id) if stuck or missed or dispatched: db.session.commit() futures = [_pool.submit(_execute, task_id) for task_id in dispatched] if wait: for future in futures: future.result() return dispatched class _TaskUser: """执行期间提供给工具的最小用户视图(不跨线程携带 ORM 对象)。""" def __init__(self, user, conversation_id=None): self.id = user.id self.conversation_id = conversation_id account = user.get_jwxt_account() or {} self._jwxt_username = str(account.get('username', '') or '') def get_jwxt_account(self): if not self._jwxt_username: return None return {'username': self._jwxt_username} def _execute(task_id: int) -> None: """在独立线程 + app 上下文里执行一个已认领的任务。""" with _app.app_context(): from app.url_manager import push_school, pop_school try: task = db.session.get(AiScheduledTask, task_id) user = db.session.get(User, task.user_id) if task else None if user: push_school(user.school_id) _execute_locked(task_id) except Exception: current_app.logger.exception('AI 定时任务执行异常 #%s', task_id) try: task = db.session.get(AiScheduledTask, task_id) if task is not None and task.status == AiScheduledTask.STATUS_RUNNING: _finish(task, AiScheduledTask.STATUS_FAILED, error='执行过程出现未预期异常') except Exception: current_app.logger.exception('AI 定时任务失败状态回写失败 #%s', task_id) finally: pop_school() def _execute_locked(task_id: int) -> None: task = db.session.get(AiScheduledTask, task_id) if task is None or task.status != AiScheduledTask.STATUS_RUNNING: return user_row = db.session.get(User, task.user_id) if user_row is None: _finish(task, AiScheduledTask.STATUS_FAILED, error='用户不存在') return from app.ai_assistant import stream_chat, get_ai_settings from app.ai_usage import record_usage stop = threading.Event() _last_check = [0.0] def cancel_check(): """每 3 秒查一次库,用户取消任务或用量超限时中止执行。""" if stop.is_set(): return True now_mono = time.monotonic() if now_mono - _last_check[0] >= 3: _last_check[0] = now_mono status = db.session.query(AiScheduledTask.status).filter( AiScheduledTask.id == task_id).scalar() if status == AiScheduledTask.STATUS_CANCELLED: stop.set() return stop.is_set() model_name = str(get_ai_settings().get('model') or '') def usage_sink(input_tokens, output_tokens): # 体验优先:执行期间超出每日限额也不中断,任务跑完自然结束; # 用量照常入账,限额继续约束之后的交互对话。 try: record_usage(task.user_id, model_name, input_tokens, output_tokens) except Exception: current_app.logger.exception('定时任务记录 AI 用量失败 #%s', task_id) # 结果写回会话:优先创建任务时的会话,否则用该用户当前会话 conversation = None if task.conversation_id: conversation = db.session.get(AiConversation, task.conversation_id) if conversation is None: conversation = AiConversation.query.filter_by(user_id=task.user_id).first() if conversation is None: conversation = AiConversation(user_id=task.user_id) db.session.add(conversation) db.session.flush() if task.conversation_id != conversation.id: task.conversation_id = conversation.id now = _naive_now() trigger_note = f'[定时任务自动触发 · 计划 {task.scheduled_at:%Y-%m-%d %H:%M} · 实际 {now:%Y-%m-%d %H:%M}]' db.session.add(AiConversationMessage( conversation_id=conversation.id, role='user', content=f'{trigger_note}\n{task.instruction}'[:4000], )) db.session.commit() recent = conversation.messages.order_by(AiConversationMessage.id.desc()).limit(20).all() messages = [{'role': item.role, 'content': item.content} for item in reversed(recent)] output_parts = [] error_message = '' for event in stream_chat( _TaskUser(user_row, conversation.id), messages, cancel_check=cancel_check, # 无人值守:创建任务即委托,写操作自动确认;ask_user 无法获得回答 confirm=lambda call_id: True, ask=lambda call_id, payload=None: {'unattended': True}, usage_sink=usage_sink, extra_system=EXECUTION_POLICY): event_type = event.get('type') if event_type == 'text_delta': output_parts.append(event.get('delta') or '') elif event_type == 'done': output_parts = [event.get('message') or ''.join(output_parts)] elif event_type == 'error': error_message = str(event.get('message') or 'AI 响应异常') result_text = ''.join(output_parts).strip() if stop.is_set() and not result_text: _finish(task, AiScheduledTask.STATUS_CANCELLED, error='任务被用户取消,执行中止') return if error_message and not result_text: _finish_or_reschedule(task, AiScheduledTask.STATUS_FAILED, error=error_message[:500]) _save_result(conversation.id, f"⏰ 定时任务执行失败:{error_message}") return _finish_or_reschedule(task, AiScheduledTask.STATUS_SUCCESS, result=result_text, error=error_message or None) _save_result(conversation.id, f"⏰ 定时任务执行结果:\n{result_text}") def _finish_or_reschedule(task, status: str, result: str = None, error: str = None) -> None: """一次性任务落终态;重复任务记录本次结果后推进到下一次(用户取消除外)。""" if task.repeat_interval and status != AiScheduledTask.STATUS_CANCELLED: _reschedule(task, result=result, error=error) else: _finish(task, status, result=result, error=error) def _finish(task, status: str, result: str = None, error: str = None) -> None: task.status = status if result is not None: task.result = result[:4000] if error is not None: task.error = error task.run_count = (task.run_count or 0) + 1 task.executed_at = _naive_now() db.session.commit() def _reschedule(task, result: str = None, error: str = None) -> None: """重复任务:保留本次结果/原因,锚定推进下一次;到期或达次数上限则结束。""" now = _naive_now() task.status = AiScheduledTask.STATUS_PENDING if result is not None: task.result = result[:4000] task.error = error task.run_count = (task.run_count or 0) + 1 task.executed_at = now task.claimed_at = None next_at = _next_occurrence(task, now) if (task.repeat_until and next_at > task.repeat_until) or \ (task.run_count or 0) >= MAX_REPEAT_RUNS: task.status = AiScheduledTask.STATUS_ENDED task.error = f'{error};' if error else '' task.error += '重复计划已到期自动结束' db.session.commit() return task.scheduled_at = next_at db.session.commit() def _save_result(conversation_id, text: str) -> None: """把执行报告作为 assistant 消息写回会话,用户下次打开对话即可看到。""" if not conversation_id or not text: return db.session.add(AiConversationMessage( conversation_id=conversation_id, role='assistant', content=text[:4000], )) db.session.commit()