Files
intelligence_system/tools/task_manager.ipynb
T

636 lines
28 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"metadata": {},
"cell_type": "markdown",
"source": "## 1. 初始化(所有操作前必须运行)",
"id": "197b1b81f5528a50"
},
{
"cell_type": "code",
"id": "initial_id",
"metadata": {
"collapsed": true,
"ExecuteTime": {
"end_time": "2025-09-12T06:19:31.379133Z",
"start_time": "2025-09-12T06:19:30.001155Z"
}
},
"source": [
"{\n",
" \"cells\": [\n",
" {\n",
" \"cell_type\": \"markdown\",\n",
" \"metadata\": {},\n",
" \"source\": [\n",
" \"# TaskManager 任务管理类\\n\",\n",
" \"任务管理核心组件,负责任务的CRUD、状态切换、手动执行等操作\"\n",
" ]\n",
" },\n",
" {\n",
" \"cell_type\": \"code\",\n",
" \"execution_count\": null,\n",
" \"metadata\": {},\n",
" \"outputs\": [],\n",
" \"source\": [\n",
" \"import pandas as pd\\n\",\n",
" \"from datetime import datetime\\n\",\n",
" \"from typing import Dict, List, Optional, Any\\n\",\n",
" \"import pytz\\n\",\n",
" \"import croniter\\n\",\n",
" \"\\n\",\n",
" \"from utils.mysql_agent import MySQLAgent\\n\",\n",
" \"from utils.logger import CrossPlatformLog\\n\",\n",
" \"from system_management.scheduler.task_scheduler import TaskScheduler\\n\"\n",
" ]\n",
" },\n",
" {\n",
" \"cell_type\": \"code\",\n",
" \"execution_count\": null,\n",
" \"metadata\": {},\n",
" \"outputs\": [],\n",
" \"source\": [\n",
" \"class TaskManager:\\n\",\n",
" \" def __init__(self, scheduler: TaskScheduler):\\n\",\n",
" \" \\\"\\\"\\\"初始化任务管理器\\n\",\n",
" \" Args:\\n\",\n",
" \" scheduler: 任务调度器实例\\n\",\n",
" \" \\\"\\\"\\\"\\n\",\n",
" \" self.scheduler = scheduler\\n\",\n",
" \" self.db = scheduler.db # 复用调度器的数据库连接\\n\",\n",
" \" self.log = CrossPlatformLog.get_logger(\\\"TaskManager\\\")\\n\",\n",
" \"\\n\",\n",
" \" def get_all_tasks(self, active_only: bool = False) -> List[Dict[str, Any]]:\\n\",\n",
" \" \\\"\\\"\\\"获取所有任务列表\\n\",\n",
" \" Args:\\n\",\n",
" \" active_only: 是否只返回活跃任务\\n\",\n",
" \" Returns:\\n\",\n",
" \" 任务字典列表\\n\",\n",
" \" \\\"\\\"\\\"\\n\",\n",
" \" try:\\n\",\n",
" \" query = \\\"SELECT * FROM main_task\\\"\\n\",\n",
" \" params = []\\n\",\n",
" \" if active_only:\\n\",\n",
" \" query += \\\" WHERE is_active = 1\\\"\\n\",\n",
" \" query += \\\" ORDER BY task_id\\\"\\n\",\n",
" \"\\n\",\n",
" \" tasks_df = self.db.query_to_df(query, params=params)\\n\",\n",
" \" return tasks_df.to_dict('records')\\n\",\n",
" \" except Exception as e:\\n\",\n",
" \" self.log.error(\\\"获取任务列表失败\\\", exc_info=True)\\n\",\n",
" \" return []\\n\",\n",
" \"\\n\",\n",
" \" def get_task_by_id(self, task_id: int) -> Optional[Dict[str, Any]]:\\n\",\n",
" \" \\\"\\\"\\\"通过ID获取任务详情\\n\",\n",
" \" Args:\\n\",\n",
" \" task_id: 任务ID\\n\",\n",
" \" Returns:\\n\",\n",
" \" 任务字典,不存在则返回None\\n\",\n",
" \" \\\"\\\"\\\"\\n\",\n",
" \" try:\\n\",\n",
" \" task_df = self.db.query_to_df(\\n\",\n",
" \" \\\"SELECT * FROM main_task WHERE task_id = %s\\\",\\n\",\n",
" \" params=(task_id,)\\n\",\n",
" \" )\\n\",\n",
" \" if task_df.empty:\\n\",\n",
" \" return None\\n\",\n",
" \" return task_df.iloc[0].to_dict()\\n\",\n",
" \" except Exception as e:\\n\",\n",
" \" self.log.error(f\\\"获取任务详情失败 (ID: {task_id})\\\")\\n\",\n",
" \" return None\\n\",\n",
" \"\\n\",\n",
" \" def update_task(self, task_id: int, updates: Dict[str, Any]) -> bool:\\n\",\n",
" \" \\\"\\\"\\\"更新任务属性\\n\",\n",
" \" Args:\\n\",\n",
" \" task_id: 任务ID\\n\",\n",
" \" updates: 需要更新的字段字典\\n\",\n",
" \" Returns:\\n\",\n",
" \" 更新是否成功\\n\",\n",
" \" \\\"\\\"\\\"\\n\",\n",
" \" if not updates:\\n\",\n",
" \" self.log.warning(\\\"未提供更新字段\\\")\\n\",\n",
" \" return False\\n\",\n",
" \"\\n\",\n",
" \" try:\\n\",\n",
" \" # 处理Cron表达式更新(需重新计算下次运行时间)\\n\",\n",
" \" if 'cron_expression' in updates or 'time_zone' in updates:\\n\",\n",
" \" task = self.get_task_by_id(task_id)\\n\",\n",
" \" if not task:\\n\",\n",
" \" return False\\n\",\n",
" \"\\n\",\n",
" \" cron_expr = updates.get('cron_expression', task['cron_expression'])\\n\",\n",
" \" time_zone = updates.get('time_zone', task['time_zone'])\\n\",\n",
" \" updates['next_run_time'] = self.scheduler._calculate_next_run_time(cron_expr, time_zone)\\n\",\n",
" \"\\n\",\n",
" \" # 执行更新\\n\",\n",
" \" self.scheduler._update_task_status(task_id, updates)\\n\",\n",
" \" self.log.info(f\\\"任务更新成功 (ID: {task_id})\\\")\\n\",\n",
" \" return True\\n\",\n",
" \" except Exception as e:\\n\",\n",
" \" self.log.error(f\\\"任务更新失败 (ID: {task_id})\\\")\\n\",\n",
" \" return False\\n\",\n",
" \"\\n\",\n",
" \" def toggle_task_status(self, task_id: int, activate: bool) -> bool:\\n\",\n",
" \" \\\"\\\"\\\"切换任务激活状态\\n\",\n",
" \" Args:\\n\",\n",
" \" task_id: 任务ID\\n\",\n",
" \" activate: True=激活, False=禁用\\n\",\n",
" \" Returns:\\n\",\n",
" \" 操作是否成功\\n\",\n",
" \" \\\"\\\"\\\"\\n\",\n",
" \" try:\\n\",\n",
" \" status = 1 if activate else 0\\n\",\n",
" \" # 激活时重新计算下次运行时间\\n\",\n",
" \" updates = {'is_active': status}\\n\",\n",
" \" if activate:\\n\",\n",
" \" task = self.get_task_by_id(task_id)\\n\",\n",
" \" if task:\\n\",\n",
" \" updates['next_run_time'] = self.scheduler._calculate_next_run_time(\\n\",\n",
" \" task['cron_expression'], task['time_zone']\\n\",\n",
" \" )\\n\",\n",
" \"\\n\",\n",
" \" self.scheduler._update_task_status(task_id, updates)\\n\",\n",
" \" self.log.info(f\\\"任务{'激活' if activate else '禁用'}成功 (ID: {task_id})\\\")\\n\",\n",
" \" return True\\n\",\n",
" \" except Exception as e:\\n\",\n",
" \" self.log.error(f\\\"任务状态切换失败 (ID: {task_id})\\\")\\n\",\n",
" \" return False\\n\",\n",
" \"\\n\",\n",
" \" def delete_task(self, task_id: int) -> bool:\\n\",\n",
" \" \\\"\\\"\\\"删除任务\\n\",\n",
" \" Args:\\n\",\n",
" \" task_id: 任务ID\\n\",\n",
" \" Returns:\\n\",\n",
" \" 删除是否成功\\n\",\n",
" \" \\\"\\\"\\\"\\n\",\n",
" \" try:\\n\",\n",
" \" # 检查任务是否存在\\n\",\n",
" \" if not self.get_task_by_id(task_id):\\n\",\n",
" \" self.log.warning(f\\\"任务不存在 (ID: {task_id})\\\")\\n\",\n",
" \" return False\\n\",\n",
" \"\\n\",\n",
" \" # 执行删除\\n\",\n",
" \" self.db.execute_sql(\\n\",\n",
" \" \\\"DELETE FROM main_task WHERE task_id = %s\\\",\\n\",\n",
" \" params=(task_id,)\\n\",\n",
" \" )\\n\",\n",
" \" self.log.info(f\\\"任务删除成功 (ID: {task_id})\\\")\\n\",\n",
" \" return True\\n\",\n",
" \" except Exception as e:\\n\",\n",
" \" self.log.error(f\\\"任务删除失败 (ID: {task_id})\\\")\\n\",\n",
" \" return False\\n\",\n",
" \"\\n\",\n",
" \" def run_task_manually(self, task_id: int) -> bool:\\n\",\n",
" \" \\\"\\\"\\\"手动执行任务\\n\",\n",
" \" Args:\\n\",\n",
" \" task_id: 任务ID\\n\",\n",
" \" Returns:\\n\",\n",
" \" 执行是否成功\\n\",\n",
" \" \\\"\\\"\\\"\\n\",\n",
" \" try:\\n\",\n",
" \" task = self.get_task_by_id(task_id)\\n\",\n",
" \" if not task:\\n\",\n",
" \" self.log.warning(f\\\"任务不存在 (ID: {task_id})\\\")\\n\",\n",
" \" return False\\n\",\n",
" \"\\n\",\n",
" \" # 标记任务为运行中\\n\",\n",
" \" self.scheduler._update_task_status(task_id, {\\n\",\n",
" \" 'is_running': 1,\\n\",\n",
" \" 'last_run_time': datetime.now()\\n\",\n",
" \" })\\n\",\n",
" \"\\n\",\n",
" \" # 执行任务逻辑\\n\",\n",
" \" self.scheduler._execute_task_logic(task)\\n\",\n",
" \"\\n\",\n",
" \" # 更新任务状态\\n\",\n",
" \" next_run_time = self.scheduler._calculate_next_run_time(\\n\",\n",
" \" task['cron_expression'], task['time_zone']\\n\",\n",
" \" )\\n\",\n",
" \" self.scheduler._update_task_status(task_id, {\\n\",\n",
" \" 'is_running': 0,\\n\",\n",
" \" 'last_run_status': 'success',\\n\",\n",
" \" 'run_count': task['run_count'] + 1,\\n\",\n",
" \" 'next_run_time': next_run_time\\n\",\n",
" \" })\\n\",\n",
" \" return True\\n\",\n",
" \" except Exception as e:\\n\",\n",
" \" self.scheduler._update_task_status(task_id, {\\n\",\n",
" \" 'is_running': 0,\\n\",\n",
" \" 'last_run_status': 'failed'\\n\",\n",
" \" })\\n\",\n",
" \" self.log.error(f\\\"任务手动执行失败 (ID: {task_id})\\\")\\n\",\n",
" \" return False\\n\",\n",
" \"\\n\",\n",
" \" def print_task_table(self, tasks: List[Dict[str, Any]]) -> None:\\n\",\n",
" \" \\\"\\\"\\\"格式化打印任务列表\\n\",\n",
" \" Args:\\n\",\n",
" \" tasks: 任务列表\\n\",\n",
" \" \\\"\\\"\\\"\\n\",\n",
" \" if not tasks:\\n\",\n",
" \" print(\\\"没有任务数据\\\")\\n\",\n",
" \" return\\n\",\n",
" \"\\n\",\n",
" \" # 转换为DataFrame并筛选显示字段\\n\",\n",
" \" df = pd.DataFrame(tasks)\\n\",\n",
" \" display_cols = [\\n\",\n",
" \" 'task_id', 'task_name', 'task_type', 'cron_expression',\\n\",\n",
" \" 'is_active', 'last_run_status', 'next_run_time'\\n\",\n",
" \" ]\\n\",\n",
" \" # 处理状态显示\\n\",\n",
" \" df['is_active'] = df['is_active'].map({1: '活跃', 0: '禁用'})\\n\",\n",
" \" print(f\\\"共 {len(df)} 个任务\\\\n\\\")\\n\",\n",
" \" print(df[display_cols].to_string(index=False))\"\n",
" ]\n",
" },\n",
" {\n",
" \"cell_type\": \"markdown\",\n",
" \"metadata\": {},\n",
" \"source\": [\n",
" \"## 使用示例\"\n",
" ]\n",
" },\n",
" {\n",
" \"cell_type\": \"code\",\n",
" \"execution_count\": null,\n",
" \"metadata\": {},\n",
" \"outputs\": [],\n",
" \"source\": [\n",
" \"# 初始化示例\\n\",\n",
" \"from config.config import ConfigManager\\n\",\n",
" \"\\n\",\n",
" \"# 加载配置\\n\",\n",
" \"config = ConfigManager()\\n\",\n",
" \"scheduler = TaskScheduler(config.get(\\\"database\\\"))\\n\",\n",
" \"manager = TaskManager(scheduler)\\n\",\n",
" \"\\n\",\n",
" \"# 1. 列出所有任务\\n\",\n",
" \"all_tasks = manager.get_all_tasks()\\n\",\n",
" \"manager.print_task_table(all_tasks)\\n\",\n",
" \"\\n\",\n",
" \"# 2. 获取单个任务详情\\n\",\n",
" \"task = manager.get_task_by_id(1)\\n\",\n",
" \"if task:\\n\",\n",
" \" print(\\\"\\\\n任务详情:\\\")\\n\",\n",
" \" for k, v in task.items():\\n\",\n",
" \" print(f\\\"{k}: {v}\\\")\\n\",\n",
" \"\\n\",\n",
" \"# 3. 更新任务Cron表达式\\n\",\n",
" \"manager.update_task(1, {'cron_expression': '0 */2 * * *'})\\n\",\n",
" \"\\n\",\n",
" \"# 4. 激活任务\\n\",\n",
" \"manager.toggle_task_status(1, activate=True)\\n\",\n",
" \"\\n\",\n",
" \"# 5. 手动执行任务\\n\",\n",
" \"manager.run_task_manually(1)\\n\",\n",
" \"\\n\",\n",
" \"# 6. 删除任务(谨慎操作)\\n\",\n",
" \"# manager.delete_task(1)\"\n",
" ]\n",
" },\n",
" {\n",
" \"cell_type\": \"markdown\",\n",
" \"metadata\": {},\n",
" \"source\": [\n",
" \"## 核心功能说明\\n\",\n",
" \"- 依赖 `TaskScheduler` 实现底层调度逻辑与数据库交互\\n\",\n",
" \"- 支持任务全生命周期管理(查询/更新/激活/执行/删除)\\n\",\n",
" \"- 内置日志记录与错误处理\\n\",\n",
" \"- 兼容Windows/macOS/Linux多平台\"\n",
" ]\n",
" }\n",
" ],\n",
" \"metadata\": {\n",
" \"kernelspec\": {\n",
" \"display_name\": \"Python 3\",\n",
" \"language\": \"python\",\n",
" \"name\": \"python3\"\n",
" },\n",
" \"language_info\": {\n",
" \"codemirror_mode\": {\n",
" \"name\": \"ipython\",\n",
" \"version\": 3\n",
" },\n",
" \"file_extension\": \".py\",\n",
" \"mimetype\": \"text/x-python\",\n",
" \"name\": \"python\",\n",
" \"nbconvert_exporter\": \"python\",\n",
" \"pygments_lexer\": \"ipython3\",\n",
" \"version\": \"3.8.10\"\n",
" }\n",
" },\n",
" \"nbformat\": 4,\n",
" \"nbformat_minor\": 4\n",
"}"
],
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'system_management.scheduler.task_manager'",
"output_type": "error",
"traceback": [
"\u001B[31m---------------------------------------------------------------------------\u001B[39m",
"\u001B[31mModuleNotFoundError\u001B[39m Traceback (most recent call last)",
"\u001B[36mCell\u001B[39m\u001B[36m \u001B[39m\u001B[32mIn[1]\u001B[39m\u001B[32m, line 8\u001B[39m\n\u001B[32m 6\u001B[39m \u001B[38;5;66;03m# 导入系统组件\u001B[39;00m\n\u001B[32m 7\u001B[39m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34;01msystem_management\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mscheduler\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mtask_scheduler\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m TaskScheduler\n\u001B[32m----> \u001B[39m\u001B[32m8\u001B[39m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34;01msystem_management\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mscheduler\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mtask_management\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m TaskManager\n\u001B[32m 9\u001B[39m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34;01mconfig\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m Config\n\u001B[32m 11\u001B[39m \u001B[38;5;66;03m# 初始化配置和管理器\u001B[39;00m\n",
"\u001B[36mFile \u001B[39m\u001B[32mD:\\Idea Project\\intelligence_system\\system_management\\scheduler\\task_management.py:4\u001B[39m\n\u001B[32m 2\u001B[39m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34;01mdatetime\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m datetime\n\u001B[32m 3\u001B[39m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34;01msystem_management\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mscheduler\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mtask_scheduler\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m TaskScheduler\n\u001B[32m----> \u001B[39m\u001B[32m4\u001B[39m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34;01msystem_management\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mscheduler\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mtask_manager\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m TaskManager\n\u001B[32m 5\u001B[39m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34;01mconfig\u001B[39;00m\u001B[34;01m.\u001B[39;00m\u001B[34;01mconfig\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m ConfigManager\n\u001B[32m 8\u001B[39m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34mmain\u001B[39m():\n\u001B[32m 9\u001B[39m \u001B[38;5;66;03m# 初始化配置和组件\u001B[39;00m\n",
"\u001B[31mModuleNotFoundError\u001B[39m: No module named 'system_management.scheduler.task_manager'"
]
}
],
"execution_count": 1
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 2. 列出任务(对应命令行 list",
"id": "8271189cef3b5f17"
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"# 列出所有任务(包括已禁用的)\n",
"def list_tasks(active_only=True):\n",
" tasks = manager.get_all_tasks(active_only)\n",
" if not tasks:\n",
" display(Markdown(\"### 没有找到任务\"))\n",
" return None\n",
"\n",
" df = pd.DataFrame(tasks)\n",
"\n",
" # 格式化日期列\n",
" if 'last_run_time' in df.columns:\n",
" df['last_run_time'] = df['last_run_time'].apply(format_datetime)\n",
" if 'next_run_time' in df.columns:\n",
" df['next_run_time'] = df['next_run_time'].apply(format_datetime)\n",
"\n",
" # 重命名列名\n",
" df = df.rename(columns={\n",
" 'task_id': '任务ID',\n",
" 'task_name': '任务名称',\n",
" 'task_type': '任务类型',\n",
" 'module_path': '模块路径',\n",
" 'cron_expression': 'Cron表达式',\n",
" 'time_zone': '时区',\n",
" 'last_run_time': '最后运行时间',\n",
" 'next_run_time': '下次运行时间',\n",
" 'last_run_status': '运行状态',\n",
" 'is_active': '是否活跃',\n",
" 'run_count': '运行次数'\n",
" })\n",
"\n",
" display(Markdown(\"### 任务列表\"))\n",
" display(HTML(df.to_html(index=False)))\n",
" return df\n",
"\n",
"# 执行:列出所有任务(包括已禁用)\n",
"list_tasks(active_only=False)\n",
"\n",
"# 或者:只列出活跃任务\n",
"# list_tasks(active_only=True)"
],
"id": "7b020af55972643"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 3. 查看任务详情(对应命令行 show)",
"id": "7780dcef67a0534c"
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"# 查看指定任务的详情\n",
"def show_task_details(task_id):\n",
" task = manager.get_task_by_id(task_id)\n",
" if not task:\n",
" display(Markdown(f\"### 未找到任务ID为 {task_id} 的任务\"))\n",
" return None\n",
"\n",
" details = [\"### 任务详情\"]\n",
" details.append(f\"**任务ID**: {task.get('task_id')}\")\n",
" details.append(f\"**任务名称**: {task.get('task_name')}\")\n",
" details.append(f\"**任务类型**: {task.get('task_type')}\")\n",
" details.append(f\"**模块路径**: {task.get('module_path')}\")\n",
" details.append(f\"**Cron表达式**: {task.get('cron_expression')}\")\n",
" details.append(f\"**时区**: {task.get('time_zone', 'Asia/Shanghai')}\")\n",
" details.append(f\"**最后运行时间**: {format_datetime(task.get('last_run_time'))}\")\n",
" details.append(f\"**下次运行时间**: {format_datetime(task.get('next_run_time'))}\")\n",
" details.append(f\"**运行状态**: {task.get('last_run_status', '未运行')}\")\n",
" details.append(f\"**是否活跃**: {'是' if task.get('is_active') else '否'}\")\n",
" details.append(f\"**运行次数**: {task.get('run_count', 0)}\")\n",
" details.append(f\"**创建时间**: {format_datetime(task.get('created_at'))}\")\n",
"\n",
" display(Markdown('\\n'.join(details)))\n",
" return task\n",
"\n",
"# 执行:查看任务ID为1的详情(替换为实际ID)\n",
"show_task_details(1)"
],
"id": "eab90de72c35429e"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 4. 添加新任务(对应命令行 add",
"id": "a313f1524f5a54bc"
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"# 添加新任务\n",
"def add_new_task(name, task_type, module_path, cron_expression, timezone=\"Asia/Shanghai\"):\n",
" try:\n",
" task_id = scheduler.add_task(\n",
" task_name=name,\n",
" task_type=task_type,\n",
" module_path=module_path,\n",
" cron_expression=cron_expression,\n",
" time_zone=timezone\n",
" )\n",
" display(Markdown(f\"### 任务添加成功!\"))\n",
" display(Markdown(f\"新任务ID: {task_id},任务名称: {name}\"))\n",
" return task_id\n",
" except Exception as e:\n",
" display(Markdown(f\"### 添加任务失败: {str(e)}\"))\n",
" return None\n",
"\n",
"# 执行:添加一个新闻采集任务\n",
"add_new_task(\n",
" name=\"每日新闻采集\",\n",
" task_type=\"collector\",\n",
" module_path=\"collectors.news_collector\",\n",
" cron_expression=\"0 9 * * *\", # 每天9点执行\n",
" timezone=\"Asia/Shanghai\"\n",
")"
],
"id": "2b2d723bb8e2784f"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 5. 更新任务属性(对应命令行 update)",
"id": "12373bcbb4a0b434"
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"# 更新任务属性\n",
"def update_task(task_id, **kwargs):\n",
" updates = {}\n",
" if 'name' in kwargs and kwargs['name']:\n",
" updates['task_name'] = kwargs['name']\n",
" if 'type' in kwargs and kwargs['type']:\n",
" updates['task_type'] = kwargs['type']\n",
" if 'module' in kwargs and kwargs['module']:\n",
" updates['module_path'] = kwargs['module']\n",
" if 'cron' in kwargs and kwargs['cron']:\n",
" updates['cron_expression'] = kwargs['cron']\n",
" if 'timezone' in kwargs and kwargs['timezone']:\n",
" updates['time_zone'] = kwargs['timezone']\n",
"\n",
" if not updates:\n",
" display(Markdown(\"### 没有提供任何更新内容\"))\n",
" return False\n",
"\n",
" success = manager.update_task(task_id, updates)\n",
" if success:\n",
" display(Markdown(f\"### 任务ID {task_id} 更新成功\"))\n",
" show_task_details(task_id) # 显示更新后的详情\n",
" else:\n",
" display(Markdown(f\"### 任务ID {task_id} 更新失败\"))\n",
" return success\n",
"\n",
"# 执行:更新任务(示例:修改任务1的Cron表达式为每天10点)\n",
"update_task(1, cron=\"0 10 * * *\")\n",
"\n",
"# 执行:同时更新多个属性(名称和Cron表达式)\n",
"# update_task(1, name=\"每日早间新闻采集\", cron=\"0 8 * * *\")"
],
"id": "c892fd8ad2f0dd9d"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 6. 启用 / 禁用任务(对应命令行 toggle",
"id": "37564011cf5aa501"
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"# 启用或禁用任务\n",
"def toggle_task_status(task_id, activate=True):\n",
" success = manager.toggle_task_status(task_id, activate)\n",
" action = \"启用\" if activate else \"禁用\"\n",
" if success:\n",
" display(Markdown(f\"### 任务ID {task_id} {action}成功\"))\n",
" else:\n",
" display(Markdown(f\"### 任务ID {task_id} {action}失败\"))\n",
" return success\n",
"\n",
"# 执行:启用任务ID为1的任务\n",
"toggle_task_status(1, activate=True)\n",
"\n",
"# 执行:禁用任务ID为1的任务\n",
"# toggle_task_status(1, activate=False)"
],
"id": "65388d10c5c8d407"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 7. 手动执行任务(对应命令行 run)",
"id": "c554c748169d5ac8"
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"# 手动执行任务\n",
"def run_task_manually(task_id):\n",
" display(Markdown(f\"### 正在手动执行任务ID {task_id}...\"))\n",
" success = manager.run_task_manually(task_id)\n",
" if success:\n",
" display(Markdown(f\"### 任务ID {task_id} 执行成功\"))\n",
" else:\n",
" display(Markdown(f\"### 任务ID {task_id} 执行失败\"))\n",
" return success\n",
"\n",
"# 执行:手动运行任务ID为1的任务\n",
"run_task_manually(1)"
],
"id": "94892f4134316f8e"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 8. 删除任务(对应命令行 delete",
"id": "c3492a1af7dbf2b1"
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": [
"# 删除任务\n",
"def delete_task(task_id, confirm=False):\n",
" if not confirm:\n",
" display(Markdown(f\"### 警告:删除任务是不可逆操作!\"))\n",
" display(Markdown(f\"请运行 `delete_task({task_id}, confirm=True)` 确认删除\"))\n",
" return False\n",
"\n",
" success = manager.delete_task(task_id)\n",
" if success:\n",
" display(Markdown(f\"### 任务ID {task_id} 删除成功\"))\n",
" else:\n",
" display(Markdown(f\"### 任务ID {task_id} 删除失败\"))\n",
" return success\n",
"\n",
"# 执行:第一步 - 确认删除(不会实际删除)\n",
"delete_task(1)\n",
"\n",
"# 执行:第二步 - 实际删除(谨慎操作!)\n",
"# delete_task(1, confirm=True)"
],
"id": "6936dcc673933a8d"
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}