Cron 表达式选择器
概述
CronSelector 是一个可视化的 Cron 表达式配置组件,用户可以通过图形界面配置定时任务的执行时间,无需手动编写 Cron 表达式。
组件路径:web/apps/web-ele/src/components/zq-form/cron-selector/
组件名称:CronSelector
功能特性
- 可视化配置:通过 Tab 页分别配置秒、分、时、日、月、周、年
- 多种配置模式:每一项支持"每"、"范围"、"循环"、"指定"等模式
- 表达式预览:实时显示生成的 Cron 表达式
- 执行时间预览:显示未来 N 次执行时间
- 支持隐藏秒/年字段
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
modelValue | string | '' | Cron 表达式 |
disabled | boolean | false | 是否禁用 |
hideSecond | boolean | true | 是否隐藏秒配置 |
hideYear | boolean | true | 是否隐藏年配置 |
placeholder | string | 'Cron表达式' | 占位符文本 |
remote | Function | - | 远程获取执行时间的函数 |
Events
| 事件 | 参数 | 说明 |
|---|---|---|
update:modelValue | string | Cron 表达式更新 |
change | string | Cron 表达式变化 |
配置模式
每个时间字段支持以下配置模式:
| 模式 | 说明 | 示例 |
|---|---|---|
EVERY | 每一个 | * |
RANGE | 范围 | 1-10 |
LOOP | 循环 | 0/5(从0开始每5个) |
SPECIFY | 指定值 | 1,3,5,7 |
UNSET | 不设置 | ? |
LAST | 最后 | L(仅日/周) |
WORK | 工作日 | W(仅日) |
Cron 表达式格式
标准 7 位 Cron 表达式:
秒 分 时 日 月 周 年示例:
0 0 12 * * ?- 每天中午 12 点0 0/30 9-17 * * ?- 工作时间每 30 分钟0 0 10 ? * MON-FRI- 周一到周五上午 10 点
使用示例
基础用法
vue
<template>
<CronSelector v-model="cronExpression" />
<p>当前表达式: {{ cronExpression }}</p>
</template>
<script setup>
import { ref } from 'vue';
const cronExpression = ref('0 0 12 * * ?');
</script>显示秒和年
vue
<template>
<CronSelector
v-model="cronExpression"
:hide-second="false"
:hide-year="false"
/>
</template>
<script setup>
import { ref } from 'vue';
const cronExpression = ref('0 0 12 * * ? 2024');
</script>自定义执行时间预览
vue
<template>
<CronSelector
v-model="cronExpression"
:remote="fetchExecutionTimes"
/>
</template>
<script setup>
import { ref } from 'vue';
const cronExpression = ref('0 0 12 * * ?');
function fetchExecutionTimes(cron, timestamp, callback) {
// 调用后端 API 获取执行时间列表
fetch(`/api/cron/preview?cron=${encodeURIComponent(cron)}×tamp=${timestamp}`)
.then(res => res.json())
.then(data => callback(data.times.join('\n')));
}
</script>禁用状态
vue
<template>
<CronSelector
v-model="cronExpression"
:disabled="true"
/>
</template>与表单设计器集成
在表单设计器中,该组件作为 cron-selector 类型的表单项使用:
json
{
"type": "cron-selector",
"field": "scheduleExpression",
"label": "执行计划",
"props": {
"hideSecond": true,
"hideYear": true,
"placeholder": "请配置执行计划"
}
}组件结构
cron-selector/
├── cron-selector.vue # 主组件(输入框 + 编辑按钮)
├── cron-modal.vue # 配置弹窗
├── tabs/ # 各时间字段配置 Tab
│ ├── SecondTab.vue
│ ├── MinuteTab.vue
│ ├── HourTab.vue
│ ├── DayTab.vue
│ ├── MonthTab.vue
│ ├── WeekTab.vue
│ └── YearTab.vue
├── types.ts # 类型定义
└── index.ts # 导出