Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: 定时任务支持 7段时间表达式,单次任务可以通过设置年份准确实现

Haowei_Dud06a87f0d679
diff --git a/docs/en/ScheduledTasks.md b/docs/en/ScheduledTasks.md
index 35d7b4fd9e..3a3a84edd2 100644
--- a/docs/en/ScheduledTasks.md
+++ b/docs/en/ScheduledTasks.md
@@ -40,8 +40,8 @@ How to create and manage a simple scheduled job in JiuwenClaw and push results t
- **Monday 09:00**: `0 9 * * 1`
- **Every hour on the hour**: `0 * * * *`
-Format: `minute hour day month weekday` (5 fields, space-separated).
-
+Format: `minute hour day month weekday` (5 fields, space-separated),
+or `minute hour day month weekday second year` (7 fields, space-separated).
---
### 4. Create via chat (optional)
diff --git "a/docs/zh/\345\256\232\346\227\266\344\273\273\345\212\241.md" "b/docs/zh/\345\256\232\346\227\266\344\273\273\345\212\241.md"
index 168d2fb16a..1e43a59352 100644
--- "a/docs/zh/\345\256\232\346\227\266\344\273\273\345\212\241.md"
+++ "b/docs/zh/\345\256\232\346\227\266\344\273\273\345\212\241.md"
@@ -45,6 +45,8 @@
Cron 表达式格式为:
`分 时 日 月 周`(5 段,空格分隔)
+或者
+`分 时 日 月 周 秒 年`(7 段,空格分隔)
---
diff --git a/jiuwenclaw/gateway/cron/controller.py b/jiuwenclaw/gateway/cron/controller.py
index 5099b3a656..c79f62baca 100644
--- a/jiuwenclaw/gateway/cron/controller.py
+++ b/jiuwenclaw/gateway/cron/controller.py
@@ -164,7 +164,15 @@ class CronController:
out: list[dict[str, Any]] = []
push_dt = base
for _ in range(count):
- push_dt = _cron_next_push_dt(job.cron_expr, push_dt)
+ try:
+ push_dt = _cron_next_push_dt(job.cron_expr, push_dt)
+ except Exception as exc: # noqa: BLE001
+ # croniter 对“单次且已到/已用完”的 7 段表达式会抛错。
+ # 预览场景希望返回已有结果(通常为 1 条),而不是让工具调用失败。
+ _msg = str(exc)
+ if "CroniterBadDateError" in _msg or "failed to find next date" in _msg:
+ break
+ raise
wake_dt = push_dt - timedelta(seconds=max(0, int(job.wake_offset_seconds or 0)))
out.append({"wake_at": wake_dt.isoformat(), "push_at": push_dt.isoformat()})
return out
@@ -266,43 +274,65 @@ class CronController:
make_tool(
name="cron_create_job",
description=(
- "创建定时任务。cron_expr 为 5 段(分 时 日 月 周)。"
- "周期任务:每天 9 点='0 9 * * *',每周一 9 点='0 9 * * 1'。"
- "相对时间(自然语言):如“过X分钟/ X分钟后提醒我”,请先用当前 timezone 的当前时间 now,计算 run_at=now+X分钟,"
- "再把 cron_expr 写成一次性日期形式 '分 时 日 月 周'。例如 run_at=2026-03-19 10:07,则 cron_expr='7 10 19 3 *'。"
- "单次任务:cron 也能表达具体日期,如今天 17 点(假设 3 月 10 日)='0 17 10 3 *',明天 15 点(3 月 11 日)='0 15 11 3 *'。根据用户当前日期推算。"
- "description 只填任务内容,不要包含时间/频率。timezone 默认 Asia/Shanghai。"
+ "Create a scheduled cron job.\n"
+ "cron_expr:\n"
+ "- Recurring (5 fields): minute hour day month day-of-week.\n"
+ " Example: daily 9:00 = '0 9 * * *', every Monday 9:00 = '0 9 * * 1'.\n"
+ "- Relative time (e.g. \"in X minutes\"): take now in the given timezone, "
+ "compute run_at = now + X minutes, then encode run_at as 7-field cron "
+ "with a fixed year (minute hour day month day-of-week second year). "
+ "Example: run_at (Mar 19, 2026 10:07:00 local) -> '0 7 10 19 3 * 2026'.\n"
+ "- One-shot (runs only once): must use 7 fields with a fixed year: "
+ "minute hour day month day-of-week second year. "
+ "Example: 2026-03-28 17:00 (local) -> '0 17 28 3 * 0 2026'.\n"
+ "Warning: if you use a 5-field expression with fixed day/month "
+ "but year semantics implicitly '*', it will repeat every year; "
+ "for a real one-shot, use the 7-field form with a fixed year.\n"
+ "description should contain task content only (no time/frequency). "
+ "timezone defaults to Asia/Shanghai."
),
input_params={
"type": "object",
"properties": {
- "name": {"type": "string", "description": "任务名称"},
+ "name": {"type": "string", "description": "Job name"},
"cron_expr": {
"type": "string",
- "description": "Cron 表达式(分 时 日 月 周)。周期用通配符如'0 9 * * *';单次用具体日期如'0 17 10 3 *'表示3月10日17点",
+ "description": (
+ "Cron expression. "
+ "Recurring jobs use 5 fields: minute hour dom month day-of-week. "
+ "One-shot jobs must use 7 fields: minute hour dom month "
+ "day-of-week second year (fixed year). "
+ "For relative time, treat it as one-shot: compute run_at = now + X minutes, "
+ "then encode it as a 7-field expression with a fixed year. "
+ "Example: 2026-03-28 17:00 (local) -> '0 17 28 3 * 0 2026'."
+ ),
},
"timezone": {
"type": "string",
- "description": "时区,如 Asia/Shanghai",
+ "description": "Time zone (IANA), e.g. Asia/Shanghai",
"default": "Asia/Shanghai",
},
"targets": {
"type": "string",
"enum": [e.value for e in CronTargetChannel],
- "description": "推送频道:web=网页, feishu=飞书, whatsapp=WhatsApp, wecom=企业微信。不传则使用当前请求来源频道",
+ "description": "Delivery channel: web, feishu, whatsapp, wecom, xiaoyi. "
+ "If omitted, use the current request source channel.",
},
"enabled": {
"type": "boolean",
- "description": "是否启用",
+ "description": "Whether the job is enabled",
"default": True,
},
"description": {
"type": "string",
- "description": "具体任务内容,到点执行时发给助手。不要包含时间/频率",
+ "description": (
+ "Task payload text sent to the assistant at run time. "
+ "Do not include time or frequency."
+ ),
},
"wake_offset_seconds": {
"type": "integer",
- "description": "提前多少秒执行,默认 60",
+ "description": "Seconds to wake before push. Default 60",
"default": 60,
},
},
@@ -312,14 +342,20 @@ class CronController:
),
make_tool(
name="cron_update_job",
- description="Update an existing cron job. Pass job_id and a patch dict with fields to update (name, enabled, cron_expr, timezone, description, wake_offset_seconds, targets).",
+ description=(
+ "Update an existing cron job. Pass job_id and a patch dict with fields to update "
+ "(name, enabled, cron_expr, timezone, description, wake_offset_seconds, targets)."
+ ),
input_params={
"type": "object",
"properties": {
"job_id": {"type": "string", "description": "Job id to update"},
"patch": {
"type": "object",
- "description": "Fields to update (name, enabled, cron_expr, timezone, description, wake_offset_seconds, targets)",
+ "description": (
+ "Fields to update (name, enabled, cron_expr, timezone, "
+ "description, wake_offset_seconds, targets)"
+ ),
"properties": {
"targets": {
"type": "string",
@@ -363,7 +399,10 @@ class CronController:
),
make_tool(
name="cron_preview_job",
- description="Preview next N scheduled run times for a job. Returns list of {wake_at, push_at} timestamps.",
+ description=(
+ "Preview next N scheduled run times for a job. "
+ "Returns list of {wake_at, push_at} timestamps."
+ ),
input_params={
"type": "object",
"properties": {
diff --git a/jiuwenclaw/gateway/cron/cron_expr.py b/jiuwenclaw/gateway/cron/cron_expr.py
new file mode 100644
index 0000000000..fb26fd32df
--- /dev/null
+++ b/jiuwenclaw/gateway/cron/cron_expr.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+from datetime import datetime
+
+from zoneinfo import ZoneInfo
+
+
+def cron_field_count(expr: str) -> int:
+ return len(str(expr or "").split())
+
+
+def iso_to_seven_field_cron(at_iso: str, *, timezone: str) -> str:
+ """Convert ISO8601 datetime into croniter 7-field cron:
+ minute hour day month dow second year.
+
+ If the input has no timezone, interpret it in `timezone`.
+ """
+ s = (at_iso or "").strip()
+ if not s:
+ raise ValueError("at_iso is empty")
+ if s.endswith("Z"):
+ s = s[:-1] + "+00:00"
+ dt = datetime.fromisoformat(s)
+ tz = ZoneInfo(timezone)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=tz)
+ else:
+ dt = dt.astimezone(tz)
+ # day-of-week is left as '*' because we fixed year/month/day.
+ return f"{dt.minute} {dt.hour} {dt.day} {dt.month} * {dt.second} {dt.year}"
+
+
+def validate_cron_expression(expr: str, *, timezone: str) -> None:
+ """Validate cron expression format is 5 or 7 fields and croniter accepts it.
+
+ Note: for 7-field one-shot with a fixed past year, `croniter.get_next()`
+ can fail; we only validate syntax here.
+ """
+ from croniter import croniter # type: ignore
+
+ raw = str(expr or "").strip()
+ if not raw:
+ raise ValueError("cron_expr is empty")
+
+ n = cron_field_count(raw)
+ if n not in (5, 7):
+ raise ValueError(
+ f"cron_expr must have 5 fields or 7 fields, got {n} fields"
+ )
+ if not croniter.is_valid(raw):
+ raise ValueError("invalid cron expression")
+ # Ensure timezone itself is valid. Do not require a future matching date.
+ _ = ZoneInfo(timezone)
+ croniter(raw, datetime.now(tz=ZoneInfo(timezone)))
diff --git a/jiuwenclaw/gateway/cron/cron_json_convert.py b/jiuwenclaw/gateway/cron/cron_json_convert.py
index 34ad3285d2..0792787115 100644
--- a/jiuwenclaw/gateway/cron/cron_json_convert.py
+++ b/jiuwenclaw/gateway/cron/cron_json_convert.py
@@ -43,7 +43,9 @@ import json
import sys
from pathlib import Path
from typing import Any
-from datetime import datetime, timezone as dt_timezone
+from datetime import datetime
+
+from jiuwenclaw.gateway.cron.cron_expr import iso_to_seven_field_cron
_EXTERNAL_TO_INTERNAL_CHANNELS: dict[str, str] = {
@@ -103,24 +105,15 @@ def convert_cron_job_dict_to_flat(data: dict[str, Any]) -> dict[str, Any]:
expr = str(sched.get("expr") or "").strip()
tz = str(sched.get("tz") or "").strip()
elif kind == "at":
- # 近似 one-shot:转成每年同一时刻的 cron(day/month 固定,weekday 为 *)
+ # one-shot:使用 croniter 的 7 段表达式固定到指定年份
at_raw = str(sched.get("at") or "").strip()
if not at_raw:
return data
- # 支持形如 2026-02-01T16:00:00Z / 2025-12-13T00:00:01.000Z
- at_norm = at_raw[:-1] + "+00:00" if at_raw.endswith("Z") else at_raw
+ tz = str(sched.get("tz") or "").strip() or "UTC"
try:
- dt = datetime.fromisoformat(at_norm)
- except ValueError:
+ expr = iso_to_seven_field_cron(at_raw, timezone=tz)
+ except Exception: # noqa: BLE001
return data
- if dt.tzinfo is None:
- # 不带时区则按 UTC 处理
- dt = dt.replace(tzinfo=dt_timezone.utc)
- else:
- dt = dt.astimezone(dt_timezone.utc)
-
- expr = f"{dt.minute} {dt.hour} {dt.day} {dt.month} *"
- tz = "UTC"
else:
return data