feat(schedule): 任务支持「每天定时 / 每周定时」,用选择器而不是手写 cron
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

- schedule.py: 新增调度计算模块(纯函数,便于单测)。三种模式:interval(每 N 分钟)/ daily(选钟点)/ weekly(选星期 + 钟点)
- 钟点模式是「固定时刻」而非「固定延迟」——从日历重算,所以某轮跑晚了不会把之后每一轮都拖晚。interval 保持原语义:从上一轮开始计时
- 抖动只加给 interval。给「每天 9:00」也加抖动就成了 9:00–9:01 随机触发,操作者选的时间被悄悄改掉,只会像 bug
- 模型 / schema / service: 新增 schedule_mode / schedule_hours / schedule_days / schedule_minute。时钟字段存逗号分隔文本——几个小整数、永远整体读写,单开一张表只会换来 join。interval_minutes 保留且仍是默认值,已有任务不受影响
- service: 改动任何调度字段都按合并后的状态重算 next_run_at。重新启用也算改动,否则停用一个月再打开会带着一个月前的 next_run_at,一保存就立即触发
- 前端: 运行方式三选一 + 小时/星期胶囊多选 + 分钟下拉,并实时预览结果句子。任务卡片改显示后端拼好的 schedule_label,避免列表和编辑器对同一计划给出两种说法
- 校验: 钟点模式至少选一个时间,按周至少选一个星期

tests/test_schedule.py 新增 24 个用例,含「恰好等于当前时刻的档位归属下一天」这个会让调度器自循环的边界。
This commit is contained in:
2026-10-07 15:33:17 +08:00
parent 242e3a7837
commit 8f4e5586e9
10 changed files with 776 additions and 22 deletions
+3 -2
View File
@@ -3,7 +3,7 @@ import { Bell, CalendarClock, Pencil, Play, Trash2 } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { useDeleteTask, useRunTaskNow, useUpdateTask } from '@/hooks/useMonitor'
import { formatInterval, formatRelative } from '@/lib/monitorFormat'
import { formatRelative } from '@/lib/monitorFormat'
import type { MonitorTask } from '@/types/monitor'
interface TaskCardProps {
@@ -82,7 +82,8 @@ export function TaskCard({ task, selected, onSelect, onEdit }: TaskCardProps) {
<span>
目标 <span className="text-cyber-neon-cyan">{task.target_count}</span> 个
</span>
<span>间隔 {formatInterval(task.interval_minutes)}</span>
{/* 由后端拼好,列表和编辑弹窗因此不会对同一个计划给出两种说法 */}
<span>{task.schedule_label}</span>
<span className="flex items-center gap-1">
<CalendarClock className="w-3 h-3" />
{task.enabled ? formatRelative(task.next_run_at) : '已暂停'}
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'
import { useEffect, useState, type ReactNode } from 'react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
@@ -20,7 +20,13 @@ import {
SelectValue,
} from '@/components/ui/select'
import { useCreateTask, useSettings, useUpdateTask } from '@/hooks/useMonitor'
import type { MonitorMode, MonitorTask, TaskCreatePayload } from '@/types/monitor'
import { describeSchedule } from '@/lib/monitorFormat'
import type {
MonitorMode,
MonitorTask,
ScheduleMode,
TaskCreatePayload,
} from '@/types/monitor'
interface TaskEditorDialogProps {
open: boolean
@@ -44,6 +50,48 @@ const INTERVAL_OPTIONS = [
{ value: '10080', label: '7 天' },
]
const SCHEDULE_MODE_OPTIONS: Array<{ value: ScheduleMode; label: string }> = [
{ value: 'interval', label: '固定间隔' },
{ value: 'daily', label: '每天定时' },
{ value: 'weekly', label: '每周定时' },
]
const HOURS = Array.from({ length: 24 }, (_, hour) => hour)
const MINUTES = Array.from({ length: 60 }, (_, minute) => minute)
const WEEKDAYS = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
const pad = (value: number) => String(value).padStart(2, '0')
function toggleNumber(values: number[], value: number): number[] {
return values.includes(value)
? values.filter((item) => item !== value)
: [...values, value].sort((a, b) => a - b)
}
/** A selectable pill. Used for the hours of the day and the weekdays. */
function Chip({
active,
onClick,
children,
}: {
active: boolean
onClick: () => void
children: ReactNode
}) {
return (
<button
type="button"
onClick={onClick}
className={`px-1.5 py-0.5 rounded border text-[10px] font-mono transition-colors ${
active
? 'border-cyber-neon-cyan/60 bg-cyber-neon-cyan/20 text-cyber-neon-cyan'
: 'border-cyber-border-DEFAULT text-cyber-text-muted hover:text-cyber-text-secondary'
}`}
>
{children}
</button>
)
}
export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogProps) {
const isEdit = Boolean(task)
const createTask = useCreateTask()
@@ -53,6 +101,10 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
const [name, setName] = useState('')
const [mode, setMode] = useState<MonitorMode>('creator')
const [intervalMinutes, setIntervalMinutes] = useState('360')
const [scheduleMode, setScheduleMode] = useState<ScheduleMode>('interval')
const [scheduleHours, setScheduleHours] = useState<number[]>([])
const [scheduleDays, setScheduleDays] = useState<number[]>([])
const [scheduleMinute, setScheduleMinute] = useState('0')
const [maxNotes, setMaxNotes] = useState('20')
const [enableComments, setEnableComments] = useState(true)
const [maxComments, setMaxComments] = useState('50')
@@ -69,6 +121,10 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
setIntervalMinutes(
String(task?.interval_minutes ?? settings?.values['collect.default_interval_minutes'] ?? 360),
)
setScheduleMode(task?.schedule_mode ?? 'interval')
setScheduleHours(task?.schedule_hours ?? [])
setScheduleDays(task?.schedule_days ?? [])
setScheduleMinute(String(task?.schedule_minute ?? 0))
setMaxNotes(
String(task?.max_notes_count ?? settings?.values['collect.default_max_notes'] ?? 20),
)
@@ -85,17 +141,35 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
.map((value) => value.trim())
.filter(Boolean)
// Switching into a clock mode with nothing chosen would be invalid, so seed a
// sensible starting point -- the operator then edits rather than fills a blank.
const selectScheduleMode = (next: ScheduleMode) => {
setScheduleMode(next)
if (next !== 'interval' && scheduleHours.length === 0) setScheduleHours([9])
if (next === 'weekly' && scheduleDays.length === 0) setScheduleDays([0, 1, 2, 3, 4])
}
const pending = createTask.isPending || updateTask.isPending
// Note-mode and creator-mode targets are different shapes, so switching mode
// would silently mis-parse the list. The backend decides parsing from the
// task's stored mode, hence mode is fixed once created.
const canSubmit = name.trim().length > 0 && targetList.length > 0 && !pending
const clockIncomplete =
scheduleMode !== 'interval' &&
(scheduleHours.length === 0 || (scheduleMode === 'weekly' && scheduleDays.length === 0))
const canSubmit =
name.trim().length > 0 && targetList.length > 0 && !pending && !clockIncomplete
const handleSubmit = () => {
const payload: TaskCreatePayload = {
name: name.trim(),
mode,
interval_minutes: Number(intervalMinutes),
schedule_mode: scheduleMode,
// Interval mode has no clock times, so send none rather than leave stale
// ones behind from a mode the operator tried and abandoned.
schedule_hours: scheduleMode === 'interval' ? [] : scheduleHours,
schedule_days: scheduleMode === 'weekly' ? scheduleDays : [],
schedule_minute: Number(scheduleMinute),
max_notes_count: Number(maxNotes),
enable_comments: enableComments,
max_comments_count: Number(maxComments),
@@ -159,6 +233,28 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
)}
</div>
<div className="space-y-2">
<Label className="text-xs font-mono text-cyber-text-secondary">运行计划</Label>
<div className="flex gap-1">
{SCHEDULE_MODE_OPTIONS.map((option) => (
<button
key={option.value}
type="button"
onClick={() => selectScheduleMode(option.value)}
className={`flex-1 rounded border px-1 py-1.5 text-[10px] font-mono transition-colors ${
scheduleMode === option.value
? 'border-cyber-neon-cyan/60 bg-cyber-neon-cyan/20 text-cyber-neon-cyan'
: 'border-cyber-border-DEFAULT text-cyber-text-muted hover:text-cyber-text-secondary'
}`}
>
{option.label}
</button>
))}
</div>
</div>
</div>
{scheduleMode === 'interval' ? (
<div className="space-y-2">
<Label className="text-xs font-mono text-cyber-text-secondary">采集间隔</Label>
<Select value={intervalMinutes} onValueChange={setIntervalMinutes}>
@@ -173,8 +269,82 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
))}
</SelectContent>
</Select>
<p className="text-[10px] font-mono text-cyber-text-muted">
从上一轮<span className="text-cyber-text-secondary">开始</span>计时,
所以某轮跑得久也不会让下一轮紧接着触发。
</p>
</div>
</div>
) : (
<div className="space-y-3 rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/40 p-3">
{scheduleMode === 'weekly' && (
<div className="space-y-1.5">
<div className="text-[10px] font-mono text-cyber-text-secondary">星期</div>
<div className="flex flex-wrap gap-1">
{WEEKDAYS.map((label, day) => (
<Chip
key={day}
active={scheduleDays.includes(day)}
onClick={() => setScheduleDays((prev) => toggleNumber(prev, day))}
>
{label}
</Chip>
))}
</div>
</div>
)}
<div className="space-y-1.5">
<div className="text-[10px] font-mono text-cyber-text-secondary">
时间(可多选,点一次选中、再点取消)
</div>
<div className="flex flex-wrap gap-1">
{HOURS.map((hour) => (
<Chip
key={hour}
active={scheduleHours.includes(hour)}
onClick={() => setScheduleHours((prev) => toggleNumber(prev, hour))}
>
{pad(hour)}
</Chip>
))}
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-[10px] font-mono text-cyber-text-secondary">分钟</span>
<Select value={scheduleMinute} onValueChange={setScheduleMinute}>
<SelectTrigger className="h-7 w-20 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent className="max-h-56">
{MINUTES.map((minute) => (
<SelectItem key={minute} value={String(minute)}>
{pad(minute)}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-[10px] font-mono text-cyber-text-muted">
所有时间点共用
</span>
</div>
<div className="flex items-center justify-between gap-3 border-t border-cyber-border-subtle pt-2">
<span className="text-[11px] font-mono text-cyber-neon-cyan">
{describeSchedule(
scheduleMode,
Number(intervalMinutes),
scheduleHours,
scheduleDays,
Number(scheduleMinute),
)}
</span>
<span className="text-[10px] font-mono text-cyber-text-muted">
按服务器本地时间
</span>
</div>
</div>
)}
<div className="space-y-2">
<Label className="text-xs font-mono text-cyber-text-secondary">
+36
View File
@@ -1,5 +1,7 @@
/** Formatting helpers for the monitoring dashboard. */
import type { ScheduleMode } from '@/types/monitor'
/** Compact count for display: mirrors how the platform itself abbreviates. */
export function formatCount(value: number | null | undefined): string {
if (value === null || value === undefined) return '—'
@@ -42,3 +44,37 @@ export function formatInterval(minutes: number): string {
if (minutes % 60 === 0) return `${minutes / 60} 小时`
return `${minutes} 分钟`
}
const WEEKDAY_NAMES = '一二三四五六日'
/**
* Preview of a schedule, for the editor only.
*
* The task list renders the backend's own `schedule_label` instead. This exists
* so the current selection can be read back before it is saved -- which means the
* two are the same sentence written twice, and a change to one belongs in both.
*/
export function describeSchedule(
mode: ScheduleMode,
intervalMinutes: number,
hours: number[],
days: number[],
minute: number,
): string {
const pad = (value: number) => String(value).padStart(2, '0')
const sorted = (values: number[]) => [...values].sort((a, b) => a - b)
if (mode === 'interval') return `每 ${formatInterval(intervalMinutes)}`
if (hours.length === 0) return '未设置时间'
const clock = sorted(hours)
.map((hour) => `${pad(hour)}:${pad(minute)}`)
.join('、')
if (mode === 'daily' || days.length === 0) return `每天 ${clock}`
const labels = sorted(days)
.map((day) => `周${WEEKDAY_NAMES[day]}`)
.join('、')
return `${labels} ${clock}`
}
+21
View File
@@ -28,6 +28,14 @@ export interface MonitorTarget {
enabled: boolean
}
/**
* How a task is scheduled.
*
* All three are expressible with pickers. A cron string is deliberately not
* supported -- it is a small language to learn just to say "every day at nine".
*/
export type ScheduleMode = 'interval' | 'daily' | 'weekly'
export interface MonitorTask {
id: number
name: string
@@ -35,6 +43,15 @@ export interface MonitorTask {
mode: MonitorMode
enabled: boolean
interval_minutes: number
schedule_mode: ScheduleMode
/** 0-23. Empty in interval mode. */
schedule_hours: number[]
/** 0-6 with Monday = 0, matching Python's `date.weekday()`. Weekly only. */
schedule_days: number[]
/** Minute past the hour, shared by every time in the schedule. */
schedule_minute: number
/** Composed by the backend, so the list and the editor cannot disagree. */
schedule_label: string
max_notes_count: number
enable_comments: boolean
max_comments_count: number
@@ -195,6 +212,10 @@ export interface TaskCreatePayload {
name: string
mode: MonitorMode
interval_minutes: number
schedule_mode: ScheduleMode
schedule_hours: number[]
schedule_days: number[]
schedule_minute: number
max_notes_count: number
enable_comments: boolean
max_comments_count: number