# taskScheduler **Repository Path**: fxh01/task-scheduler ## Basic Information - **Project Name**: taskScheduler - **Description**: 与AI合作生成任务调度包 - **Primary Language**: Python - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-10 - **Last Updated**: 2026-03-29 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # taskScheduler #### 介绍 与AI合作生成任务调度包 #### 需求文档✅ ✅**技术选型与架构设计**(先决定用什么技术栈,如:Python/Go/Java?Vue/React?数据库用SQLite?) ✅数据库表字段设计 ✅接口设计 ✅**后端接口文档**(定义数据结构、API 接口,这是前后端沟通的桥梁)。 1. **UI 原型与设计**(确定页面长什么样)。 2. **前端开发文档**(基于 UI 和 API 进行页面逻辑设计)。 ``` task-scheduler/ ├── app/ │ ├── __init__.py │ ├── cli.py # 命令行启动器 │ ├── decorators.py # 装饰器实现 │ ├── auth.py # 权限控制 │ ├── models.py # 数据模型 │ ├── schemas.py # Pydantic schemas │ ├── database.py # 数据库配置 │ ├── scheduler.py # 任务调度器 │ ├── executor.py # 任务执行器 │ ├── registry.py # 任务注册器 │ ├── services/ │ │ ├── __init__.py │ │ ├── task_service.py │ │ └── log_service.py │ ├── api/ │ │ ├── __init__.py │ │ ├── task_api.py │ │ ├── log_api.py │ │ ├── system_api.py │ │ └── config_api.py # 配置管理API │ └── main.py # 应用入口 ├── tests/ # 单元测试 │ ├── conftest.py │ ├── models/ │ ├── services/ │ ├── api/ │ ├── scheduler/ │ └── integration/ ├── static/ # 前端页面 │ ├── index.html # 任务管理页面 │ ├── logs.html # 执行日志页面 │ ├── login.html # 登录页面 │ └── js/ │ └── common.js # 公共JS ├── setup.py # 包化部署配置 ├── requirements.txt └── README.md ``` --- ## 快速开始 ### 环境要求 - Python 3.8+ - SQLite ### 1. 安装依赖 ```bash # 安装项目依赖 pip install -r requirements.txt # 安装开发测试依赖(可选) pip install -r requirements-dev.txt ``` ### 2. 启动Web服务 ```bash # 方式一:使用uvicorn直接启动(推荐) uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 # 方式二:使用Python模块方式启动 python -m app.main # 方式三:使用CLI命令启动 python -m app.cli ``` #### 关闭Web服务 ```bash # 方式一:使用Ctrl+C停止 # 在运行uvicorn的终端按 Ctrl+C # 方式二:查找进程并kill # 查找进程 ps aux | grep uvicorn # 杀死进程 kill # 方式三:使用pkill直接杀死 pkill -f "uvicorn app.main:app" ``` 服务启动后访问: - **前端页面**: http://localhost:8000/ - **API文档**: http://localhost:8000/docs - **ReDoc文档**: http://localhost:8000/redoc ### 3. 默认登录账号 - **用户名**: `admin` - **密码**: `admin123` --- ## 功能说明 ### 任务管理 1. **创建任务**:支持三种任务类型 - **Shell任务**:执行Shell命令 - **HTTP任务**:发送HTTP请求 - **装饰器任务**:执行Python函数 2. **触发方式**: - **Cron表达式**:按时间计划执行(如每天10:00) - **间隔触发**:按固定间隔执行(如每分钟) - **指定时间**:在指定时间执行一次 3. **任务操作**: - 查看任务列表和详情 - 启用/禁用任务 - 立即执行任务 - 编辑/删除任务 ### 执行日志 - 记录每次任务执行的结果 - 支持按任务名称、状态、执行类型筛选 - 查看执行详情(输出、错误信息、耗时等) filterwarnings = ignore::ResourceWarning ignore::DeprecationWarning- 统计功能(成功率、平均耗时等) - **批量删除**日志 - **自动刷新**(每2秒) ### 系统配置 - 可配置调度器参数(最大实例数、错过执行宽限期) - 可配置执行器参数(Shell/HTTP任务默认超时时间) - 可配置日志保留天数 - 可配置Token过期时间 - 支持**自定义配置项** --- ## 更新日志 ### 2026-03-12 #### 新增功能 - 系统配置管理页面(`/config.html`) - 批量删除执行日志功能 - 按任务名称搜索日志 - 状态/类型筛选功能 - 自动刷新(任务列表、执行日志每2秒) #### 优化改进 - 任务查看功能:输入框置灰、只显示"关闭"按钮 - Shell任务支持配置超时时间 - 登录页面修复API路径 - 登录密码自动转小写 #### 代码改进 - 新增配置管理API(`/api/v1/config/`) - 数据库初始化6个默认系统配置 ## 任务调度使用示例 ### 方式一:使用Web界面创建任务 1. 登录系统后,点击"创建任务" 2. 填写任务配置信息: - 任务名称:如 `每日备份任务` - 任务类型:Shell / HTTP / Decorator - 触发类型:Cron / Interval / Date - 执行配置:根据任务类型填写相应的配置 ### 方式二:使用装饰器定义任务 在代码中使用装饰器来定义定时任务: ```python # task_example.py from app.decorators import cron_task, interval_task, date_task import logging logger = logging.getLogger(__name__) # 方式一:Cron表达式任务(每天凌晨0点执行) @cron_task( name="每日数据清理", expression="0 0 * * *", timezone="Asia/Shanghai", timeout=3600, retry=2, retry_interval=60 ) def daily_cleanup(): """每日数据清理任务""" logger.info("开始执行每日数据清理...") # 在这里编写任务逻辑 result = cleanup_old_data() logger.info(f"清理完成,结果: {result}") return result # 方式二:间隔任务(每5分钟执行一次) @interval_task( name="健康检查", minutes=5, timeout=30 ) def health_check(): """系统健康检查任务""" logger.info("执行系统健康检查...") # 检查系统状态 return {"status": "healthy", "timestamp": "2026-01-01"} # 方式三:单次任务(在指定时间执行一次) @date_task( name="一次性备份任务", run_date="2026-01-15T10:00:00", timeout=7200 ) def one_time_backup(): """一次性备份任务""" logger.info("执行一次性备份...") return {"backup": "completed"} ``` 然后在应用中导入这些任务: ```python # app/main.py 或其他入口文件 from task_example import daily_cleanup, health_check, one_time_backup # 任务会在应用启动时自动注册到调度器 ``` ### 方式三:使用API创建任务 通过API接口创建任务: ```bash # 1. 先登录获取token curl -X POST http://localhost:8000/api/v1/system/login \ -H "Content-Type: application/json" \ -d '{"username": "admin", "password": "admin123"}' # 2. 使用token创建Shell任务 curl -X POST http://localhost:8000/api/v1/tasks \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "task_name": "测试Shell任务", "task_type": "shell", "trigger_type": "interval", "trigger_config": {"seconds": 60}, "execution_config": {"command": "echo hello world"}, "concurrency_strategy": "skip", "concurrency_config": {"max_parallel": 1}, "misfire_strategy": "skip" }' # 3. 使用token创建HTTP任务 curl -X POST http://localhost:8000/api/v1/tasks \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "task_name": "HTTP监控任务", "task_type": "http", "trigger_type": "cron", "trigger_config": {"expression": "*/5 * * * *"}, "execution_config": { "url": "https://api.example.com/health", "method": "GET", "timeout": 30 }, "concurrency_strategy": "skip", "misfire_strategy": "skip" }' ``` ### 触发类型说明 | 触发类型 | 说明 | 配置示例 | |---------|------|---------| | `cron` | Cron表达式触发 | `{"expression": "0 0 * * *", "timezone": "Asia/Shanghai"}` | | `interval` | 固定间隔触发 | `{"seconds": 60}` 或 `{"minutes": 5, "hours": 1}` | | `date` | 指定时间触发 | `{"run_date": "2026-01-01T00:00:00"}` | ### 任务类型说明 | 任务类型 | 说明 | 执行配置示例 | |---------|------|-------------| | `shell` | Shell命令任务 | `{"command": "echo hello", "timeout": 60}` | | `http` | HTTP请求任务 | `{"url": "http://example.com", "method": "GET", "timeout": 30}` | | `decorator` | 装饰器任务 | `{"func_path": "module.function_name"}` | --- ## 运行单元测试 ### 安装测试依赖 ```bash pip install -r requirements-dev.txt ``` ### 运行所有测试 ```bash pytest ``` ### 运行特定层级的测试 ```bash # 模型层测试 pytest tests/models/ -v # 服务层测试 pytest tests/services/ -v # API层测试 pytest tests/api/ -v # 调度器层测试 pytest tests/scheduler/ -v # 集成测试 pytest tests/integration/ -v ``` ### 生成Allure测试报告 ```bash # 运行测试并生成Allure结果 pytest --alluredir=./allure-results # 查看Allure报告(需要安装allure命令行工具) allure serve ./allure-results # 生成HTML报告 allure generate ./allure-results -o ./allure-report --clean ``` ### 生成代码覆盖率报告 ```bash # 运行测试并生成覆盖率报告 pytest --cov=app --cov-report=html # 查看报告 open htmlcov/index.html # macOS # 或者 start htmlcov/index.html # Windows ``` --- ## API接口列表 ### 系统接口 | 方法 | 路径 | 说明 | |------|------|------| | POST | `/api/v1/system/login` | 用户登录 | | POST | `/api/v1/system/logout` | 用户登出 | | GET | `/api/v1/system/health` | 健康检查 | | POST | `/api/v1/system/scheduler/start` | 启动调度器 | | POST | `/api/v1/system/scheduler/stop` | 停止调度器 | | GET | `/api/v1/system/scheduler/status` | 调度器状态 | ### 任务接口 | 方法 | 路径 | 说明 | |------|------|------| | GET | `/api/v1/tasks/` | 获取任务列表(分页) | | POST | `/api/v1/tasks/` | 创建任务 | | GET | `/api/v1/tasks/{task_id}` | 获取任务详情 | | PUT | `/api/v1/tasks/{task_id}` | 更新任务 | | DELETE | `/api/v1/tasks/{task_id}` | 删除任务 | | POST | `/api/v1/tasks/{task_id}/enable` | 启用任务 | | POST | `/api/v1/tasks/{task_id}/disable` | 禁用任务 | | POST | `/api/v1/tasks/{task_id}/run` | 立即执行任务 | | GET | `/api/v1/tasks/{task_id}/logs` | 获取任务日志 | ### 日志接口 | 方法 | 路径 | 说明 | |------|------|------| | GET | `/api/v1/logs/` | 获取日志列表(分页) | | GET | `/api/v1/logs/{log_id}` | 获取日志详情 | | DELETE | `/api/v1/logs/clean` | 清理历史日志 | | DELETE | `/api/v1/logs/batch` | 批量删除日志 | | GET | `/api/v1/logs/statistics` | 获取统计信息 | ### 配置接口 | 方法 | 路径 | 说明 | |------|------|------| | GET | `/api/v1/config/` | 获取配置列表(分页) | | GET | `/api/v1/config/{config_key}` | 获取单个配置 | | POST | `/api/v1/config/` | 创建配置 | | PUT | `/api/v1/config/{config_key}` | 更新配置 | | DELETE | `/api/v1/config/{config_key}` | 删除配置 | --- ## API接口详细说明 ### 系统接口 #### 1. 用户登录 ``` POST /api/v1/system/login Content-Type: application/json 请求体: { "username": "admin", "password": "admin123" } 响应: { "code": 0, "message": "success", "data": { "access_token": "eyJhbGc...", "refresh_token": "eyJhbGc...", "token_type": "bearer", "expires_at": 1773327799 } } ``` #### 2. 健康检查 ``` GET /api/v1/system/health 响应: { "code": 0, "message": "success", "data": { "status": "healthy", "scheduler_running": true, "db_connected": true } } ``` #### 3. 调度器状态 ``` GET /api/v1/system/scheduler/status 响应: { "code": 0, "message": "success", "data": { "running": true, "pending_jobs": 2, "executed_jobs": 100 } } ``` ### 任务接口 #### 4. 创建任务 ``` POST /api/v1/tasks/ Authorization: Bearer Content-Type: application/json 请求体: { "task_name": "测试任务", "task_type": "shell", "trigger_type": "interval", "trigger_config": {"seconds": 60}, "execution_config": {"command": "echo hello", "timeout": 30}, "concurrency_strategy": "skip", "concurrency_config": {"max_parallel": 1}, "misfire_strategy": "skip" } 响应: { "code": 0, "message": "success", "data": { "task_id": 1, "task_uuid": "550e8400-e29b-41d4-a716-446655440000", "task_name": "测试任务", "task_type": "shell", "status": "enabled", ... } } ``` #### 5. 获取任务列表 ``` GET /api/v1/tasks/?page=1&page_size=20 Authorization: Bearer 响应: { "code": 0, "message": "success", "data": { "total": 10, "page": 1, "page_size": 20, "items": [...] } } ``` #### 6. 立即执行任务 ``` POST /api/v1/tasks/{task_id}/run Authorization: Bearer 响应: { "code": 0, "message": "success", "data": { "log_id": 100, "message": "任务已触发执行" } } ``` ### 日志接口 #### 7. 获取日志列表 ``` GET /api/v1/logs/?page=1&page_size=20&task_name=测试任务&status=success Authorization: Bearer 响应: { "code": 0, "message": "success", "data": { "total": 100, "page": 1, "page_size": 20, "items": [ { "log_id": 1, "task_id": 1, "task_info": { "task_id": 1, "task_name": "测试任务", "task_type": "shell" }, "execution_type": "manual", "status": "success", "start_time": "2026-03-12T10:00:00", "end_time": "2026-03-12T10:00:01", "duration": 1.0, "stdout": "hello\n", "stderr": "", ... } ] } } ``` #### 8. 获取统计信息 ``` GET /api/v1/logs/statistics/?days=7 Authorization: Bearer 响应: { "code": 0, "message": "success", "data": { "total_executions": 1000, "success_count": 950, "failed_count": 50, "timeout_count": 5, "avg_duration": 1.5, "success_rate": 95.0, "daily_stats": [...] } } ``` --- ## 配置说明 ### 环境变量 可以在项目根目录创建 `.env` 文件配置环境变量: ```env # 数据库配置 DATABASE_URL=sqlite:///./task_scheduler.db # JWT配置 SECRET_KEY=your-secret-key-change-in-production ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=120 # 其他配置 DEBUG=True LOG_LEVEL=INFO ``` ### 任务调度配置 任务的并发策略: - `skip`: 跳过(默认) - `parallel`: 并行执行 - `queue`: 队列执行 任务的错过执行策略: - `skip`: 跳过(默认) - `run_now`: 立即执行 --- ## 目录结构说明 ``` task-scheduler/ ├── app/ # 应用核心代码 │ ├── api/ # API接口层 │ │ ├── task_api.py # 任务相关接口 │ │ ├── log_api.py # 日志相关接口 │ │ └── system_api.py # 系统相关接口 │ ├── services/ # 业务逻辑层 │ │ ├── task_service.py │ │ └── log_service.py │ ├── models.py # 数据模型(SQLAlchemy) │ ├── schemas.py # Pydantic schemas(数据验证) │ ├── database.py # 数据库配置 │ ├── scheduler.py # 任务调度器(APScheduler) │ ├── executor.py # 任务执行器 │ ├── decorators.py # 任务装饰器 │ ├── registry.py # 任务注册器 │ ├── auth.py # 认证授权 │ └── main.py # 应用入口 ├── tests/ # 单元测试 │ ├── conftest.py # pytest配置 │ ├── models/ # 模型测试 │ ├── services/ # 服务层测试 │ ├── api/ # API层测试 │ ├── scheduler/ # 调度器测试 │ └── integration/ # 集成测试 ├── static/ # 前端静态文件 │ ├── index.html # 任务管理页面 │ ├── logs.html # 执行日志页面 │ ├── login.html # 登录页面 │ └── js/ │ └── common.js # 公共JavaScript ├── 项目文档/ # 项目文档 └── README.md # 项目说明 ``` --- ## 常见问题 ### 1. 任务没有执行 - 检查任务状态是否为"启用" - 检查触发配置是否正确 - 查看日志中的错误信息 ### 2. 登录失败 - 确认使用正确的用户名和密码 - 检查JWT配置是否正确 ### 3. 数据库问题 - 确保SQLite文件有写权限 - 可以删除 `task_scheduler.db` 重新初始化