Skip to content

Cron 表达式选择器

概述

CronSelector 是一个可视化的 Cron 表达式配置组件,用户可以通过图形界面配置定时任务的执行时间,无需手动编写 Cron 表达式。

组件路径web/apps/web-ele/src/components/zq-form/cron-selector/

组件名称CronSelector

功能特性

  • 可视化配置:通过 Tab 页分别配置秒、分、时、日、月、周、年
  • 多种配置模式:每一项支持"每"、"范围"、"循环"、"指定"等模式
  • 表达式预览:实时显示生成的 Cron 表达式
  • 执行时间预览:显示未来 N 次执行时间
  • 支持隐藏秒/年字段

Props

属性类型默认值说明
modelValuestring''Cron 表达式
disabledbooleanfalse是否禁用
hideSecondbooleantrue是否隐藏秒配置
hideYearbooleantrue是否隐藏年配置
placeholderstring'Cron表达式'占位符文本
remoteFunction-远程获取执行时间的函数

Events

事件参数说明
update:modelValuestringCron 表达式更新
changestringCron 表达式变化

配置模式

每个时间字段支持以下配置模式:

模式说明示例
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)}&timestamp=${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             # 导出

Released under the MIT License.