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

fix: cron tool supports seven-segment expressions

wncbdj8147626a03ae
diff --git a/jiuwenclaw/agentserver/tools/cron_tools.py b/jiuwenclaw/agentserver/tools/cron_tools.py
index 0f3873821f..6aca506c58 100644
--- a/jiuwenclaw/agentserver/tools/cron_tools.py
+++ b/jiuwenclaw/agentserver/tools/cron_tools.py
@@ -332,6 +332,8 @@ class CronTools:
if "CroniterBadDateError" in msg or "failed to find next date" in msg:
break
raise
+ if out and push_dt.isoformat() == out[-1]["push_at"]:
+ break
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
diff --git a/jiuwenclaw/gateway/cron/controller.py b/jiuwenclaw/gateway/cron/controller.py
index 404663bb97..0838dd3e71 100644
--- a/jiuwenclaw/gateway/cron/controller.py
+++ b/jiuwenclaw/gateway/cron/controller.py
@@ -208,12 +208,12 @@ class CronController:
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
+ if out and push_dt.isoformat() == out[-1]["push_at"]:
+ break
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
diff --git a/jiuwenclaw/gateway/cron/cron_expr.py b/jiuwenclaw/gateway/cron/cron_expr.py
index fb26fd32df..ff38dcd1ef 100644
--- a/jiuwenclaw/gateway/cron/cron_expr.py
+++ b/jiuwenclaw/gateway/cron/cron_expr.py
@@ -10,8 +10,8 @@ def cron_field_count(expr: str) -> int:
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.
+ """Convert ISO8601 datetime into 7-field cron (Quartz format):
+ second minute hour day month dow year.
If the input has no timezone, interpret it in `timezone`.
"""
@@ -26,12 +26,11 @@ def iso_to_seven_field_cron(at_iso: str, *, timezone: str) -> str:
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}"
+ return f"{dt.second} {dt.minute} {dt.hour} {dt.day} {dt.month} ? {dt.year}"
def validate_cron_expression(expr: str, *, timezone: str) -> None:
- """Validate cron expression format is 5 or 7 fields and croniter accepts it.
+ """Validate cron expression format is 7 fields (Quartz format: second minute hour day month dow year).
Note: for 7-field one-shot with a fixed past year, `croniter.get_next()`
can fail; we only validate syntax here.
@@ -43,12 +42,12 @@ def validate_cron_expression(expr: str, *, timezone: str) -> None:
raise ValueError("cron_expr is empty")
n = cron_field_count(raw)
- if n not in (5, 7):
+ if n != 7:
raise ValueError(
- f"cron_expr must have 5 fields or 7 fields, got {n} fields"
+ f"cron_expr must have 7 fields (second minute hour day month dow year), got {n} fields"
)
- if not croniter.is_valid(raw):
+ # Use second_at_beginning=True for Quartz 7-field format
+ if not croniter.is_valid(raw, second_at_beginning=True):
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)))
+ croniter(raw, datetime.now(tz=ZoneInfo(timezone)), second_at_beginning=True)
diff --git a/jiuwenclaw/gateway/cron/scheduler.py b/jiuwenclaw/gateway/cron/scheduler.py
index 63de1181eb..c6108f8382 100644
--- a/jiuwenclaw/gateway/cron/scheduler.py
+++ b/jiuwenclaw/gateway/cron/scheduler.py
@@ -51,7 +51,12 @@ def _cron_next_push_dt(cron_expr: str, base_dt: datetime) -> datetime:
# Lazy import so the rest of the system can still run without cron enabled.
from croniter import croniter # type: ignore
- it = croniter(cron_expr, base_dt)
+ # Support Quartz 7-field format: second minute hour day month dow year
+ # croniter default is minute hour day month dow second year
+ field_count = len(cron_expr.strip().split())
+ second_at_beginning = field_count == 7
+
+ it = croniter(cron_expr, base_dt, second_at_beginning=second_at_beginning)
nxt = it.get_next(datetime)
if not isinstance(nxt, datetime):
raise RuntimeError("croniter returned invalid datetime")
diff --git a/jiuwenclaw/web/src/components/CronPanel/index.tsx b/jiuwenclaw/web/src/components/CronPanel/index.tsx
index ea44a88952..eaa21cb2d1 100644
--- a/jiuwenclaw/web/src/components/CronPanel/index.tsx
+++ b/jiuwenclaw/web/src/components/CronPanel/index.tsx
@@ -98,8 +98,9 @@ function renderScheduleSummary(job: CronJob): string {
return job.cron_expr || '';
}
-function isValidCronField(value: string, min: number, max: number, stepDivisor: number | null): { valid: boolean; error?: string } {
+function isValidCronField(value: string, min: number, max: number, stepDivisor: number | null, allowQuestion: boolean = false): { valid: boolean; error?: string } {
if (value === '*') return { valid: true };
+ if (allowQuestion && value === '?') return { valid: true };
const parts = value.split(',');
for (const part of parts) {
if (part.includes('/')) {
@@ -121,16 +122,16 @@ function isValidCronField(value: string, min: number, max: number, stepDivisor:
}
function getFieldError(min: number, max: number): string {
- if (min === 0 && max === 59) return 'cron.errors.cronMinute';
+ if (min === 0 && max === 59) return 'cron.errors.cronSecondOrMinute';
if (min === 0 && max === 23) return 'cron.errors.cronHour';
if (min === 1 && max === 31) return 'cron.errors.cronDay';
if (min === 1 && max === 12) return 'cron.errors.cronMonth';
- if (min === 0 && max === 6) return 'cron.errors.cronWeek';
+ if (min === 1 && max === 7) return 'cron.errors.cronWeek';
return 'cron.errors.cronFormat';
}
function getStepRangeError(min: number, max: number): string {
- if (min === 0 && max === 59) return 'cron.errors.cronMinuteStep';
+ if (min === 0 && max === 59) return 'cron.errors.cronSecondOrMinuteStep';
if (min === 0 && max === 23) return 'cron.errors.cronHourStep';
return getFieldError(min, max);
}
@@ -147,10 +148,14 @@ function isValidCronRange(range: string, min: number, max: number): boolean {
function validateCronExpr(expr: string): { valid: boolean; error?: string } {
const parts = expr.trim().split(/\s+/);
- if (parts.length !== 5) {
+ if (parts.length !== 7) {
return { valid: false, error: 'cron.errors.cronFormat' };
}
- const [minute, hour, day, month, week] = parts;
+ const [second, minute, hour, day, month, week, year] = parts;
+ const secondResult = isValidCronField(second, 0, 59, 60);
+ if (!secondResult.valid) {
+ return { valid: false, error: secondResult.error };
+ }
const minuteResult = isValidCronField(minute, 0, 59, 60);
if (!minuteResult.valid) {
return { valid: false, error: minuteResult.error };
@@ -159,7 +164,7 @@ function validateCronExpr(expr: string): { valid: boolean; error?: string } {
if (!hourResult.valid) {
return { valid: false, error: hourResult.error };
}
- const dayResult = isValidCronField(day, 1, 31, null);
+ const dayResult = isValidCronField(day, 1, 31, null, true);
if (!dayResult.valid) {
return { valid: false, error: dayResult.error };
}
@@ -167,10 +172,16 @@ function validateCronExpr(expr: string): { valid: boolean; error?: string } {
if (!monthResult.valid) {
return { valid: false, error: monthResult.error };
}
- const weekResult = isValidCronField(week, 0, 6, null);
+ const weekResult = isValidCronField(week, 1, 7, null, true);
if (!weekResult.valid) {
return { valid: false, error: weekResult.error };
}
+ if (year !== '*') {
+ const yearNum = parseInt(year, 10);
+ if (isNaN(yearNum) || yearNum < 1970 || yearNum > 2099) {
+ return { valid: false, error: 'cron.errors.cronYear' };
+ }
+ }
return { valid: true };
}
diff --git a/jiuwenclaw/web/src/i18n/locales/en.json b/jiuwenclaw/web/src/i18n/locales/en.json
index 31f6f1996e..38d81aa9eb 100644
--- a/jiuwenclaw/web/src/i18n/locales/en.json
+++ b/jiuwenclaw/web/src/i18n/locales/en.json
@@ -565,8 +565,8 @@
},
"placeholders": {
"name": "Enter task name",
- "cron": "Five fields: min hour day month weekday. Example: every day at 9 AM = '0 9 * * *'; every Monday at 11:58 AM = '58 11 * * 1'",
- "cronShort": "Five fields: min hour day month weekday.",
+ "cron": "7 fields (Quartz): second minute hour day month dow year. Ranges: second(0-59), minute(0-59), hour(0-23), day(1-31), month(1-12), dow(1-7 or ?), year(1970-2099 or *). Day and dow cannot both be specific. Examples: daily 9am='0 0 9 * * ? *'; one-shot 2026-04-29 17:30='0 30 17 29 4 ? 2026'",
+ "cronShort": "7 fields (Quartz): second minute hour day month dow year",
"description": "Enter description",
"wakeOffset": "Wake offset in seconds"
},
@@ -601,14 +601,15 @@
"loadDetailFailed": "Failed to load task details",
"nameRequired": "Task name is required",
"cronRequired": "Cron expression is required",
- "cronFormat": "Invalid cron format (should be: minute hour day month week)",
- "cronMinute": "Invalid minute field (0-59, supports * / - ,)",
- "cronMinuteStep": "Minute step must divide 60 (e.g. */5 */10 */15 */20 */30)",
+ "cronFormat": "Invalid cron format (must be 7 fields: second minute hour day month dow year)",
+ "cronSecondOrMinute": "Invalid second/minute field (0-59, supports * / - ,)",
+ "cronSecondOrMinuteStep": "Second/minute step must divide 60",
"cronHour": "Invalid hour field (0-23, supports * / - ,)",
- "cronHourStep": "Hour step must divide 24 (e.g. */1 */2 */3 */4 */6 */12)",
- "cronDay": "Invalid day field (1-31, supports * - ,)",
+ "cronHourStep": "Hour step must divide 24",
+ "cronDay": "Invalid day field (1-31, supports * ? - ,)",
"cronMonth": "Invalid month field (1-12, supports * - ,)",
- "cronWeek": "Invalid week field (0-6, supports * - ,)",
+ "cronWeek": "Invalid dow field (1-7, supports * ? - ,, 1=SUN)",
+ "cronYear": "Invalid year field (1970-2099 or *)",
"timezoneRequired": "Time zone is required",
"targetRequired": "Target channel is required",
"descriptionRequired": "Description is required"
diff --git a/jiuwenclaw/web/src/i18n/locales/zh.json b/jiuwenclaw/web/src/i18n/locales/zh.json
index c9edabef5f..05e63877df 100644
--- a/jiuwenclaw/web/src/i18n/locales/zh.json
+++ b/jiuwenclaw/web/src/i18n/locales/zh.json
@@ -565,8 +565,8 @@
},
"placeholders": {
"name": "输入任务名称",
- "cron": "5段式:分 时 日 月 周。例:每天9点='0 9 * * *';每周一11时58分='58 11 * * 1'",
- "cronShort": "5段式:分 时 日 月 周。",
+ "cron": "7段式(Quartz):秒 分 时 日 月 周 年。取值:秒(0-59)、分(0-59)、时(0-23)、日(1-31)、月(1-12)、周(1-7或?)、年(1970-2099或*)。日和周不能同时指定值。例:每天9点='0 0 9 * * ? *';一次性2026年4月29日17:30='0 30 17 29 4 ? 2026'",
+ "cronShort": "7段式(Quartz):秒 分 时 日 月 周 年",
"description": "输入描述",
"wakeOffset": "唤醒偏移秒数"
},
@@ -601,14 +601,15 @@
"loadDetailFailed": "获取任务详情失败",
"nameRequired": "任务名称不能为空",
"cronRequired": "Cron 表达式不能为空",
- "cronFormat": "Cron 表达式格式错误(应为:分 时 日 月 周)",
- "cronMinute": "分钟字段错误(取值 0-59,支持 * / - ,)",
- "cronMinuteStep": "分钟步长需能被60整除(如 */5 */10 */15 */20 */30)",
+ "cronFormat": "Cron 表达式格式错误(应为7段式:秒 分 时 日 月 周 年)",
+ "cronSecondOrMinute": "秒/分字段错误(取值 0-59,支持 * / - ,)",
+ "cronSecondOrMinuteStep": "秒/分步长需能被60整除",
"cronHour": "小时字段错误(取值 0-23,支持 * / - ,)",
- "cronHourStep": "小时步长需能被24整除(如 */1 */2 */3 */4 */6 */12)",
- "cronDay": "日字段错误(取值 1-31,支持 * - ,)",
+ "cronHourStep": "小时步长需能被24整除",
+ "cronDay": "日字段错误(取值 1-31,支持 * ? - ,)",
"cronMonth": "月字段错误(取值 1-12,支持 * - ,)",
- "cronWeek": "周字段错误(取值 0-6,支持 * - ,)",
+ "cronWeek": "周字段错误(取值 1-7,支持 * ? - ,,1=SUN)",
+ "cronYear": "年份字段错误(取值 1970-2099 或 *)",
"timezoneRequired": "时区不能为空",
"targetRequired": "推送频道不能为空",
"descriptionRequired": "描述不能为空"