要实现一个函数,该函数接受时间和重复时间(日、周、月、年)作为参数,并返回一个Cron表达式,可以按照以下方式编写这个函数:
export const generateCronExpression = (time: Date | string | number, repeatInterval: string) => {
const now = new Date(time)
let cronExpression = ''
// 秒
cronExpression += now.getSeconds() + ' '
// 分
cronExpression += now.getMinutes() + ' '
// 时
cronExpression += now.getHours() + ' '
// 日
if (['month', 'year'].includes(repeatInterval)) {
cronExpression += now.getDate() + ' '
} else {
cronExpression += '* '
}
// 月
if (['year'].includes(repeatInterval)) {
cronExpression += now.getMonth() + 1 + ' '
} else {
cronExpression += '* '
}
// 星期几
if (repeatInterval === 'week') {
cronExpression += now.getDay() + ' '
} else {
cronExpression += '? '
}
// 年
// if (repeatInterval === 'year') {
// const year = now.getFullYear()
// cronExpression += `${year}-${year}` + ' '
// } else {
cronExpression += '* '
// }
return cronExpression.trim()
}
// 使用示例
const time = new Date();
console.log(generateCronExpression(time, '日')); // 输出类似于 "30 45 15 * * ? " 的Cron表达式
console.log(generateCronExpression(time, '周')); // 输出类似于 "30 45 15 * * 1 " 的Cron表达式
console.log(generateCronExpression(time, '月')); // 输出类似于 "30 45 15 6 * ? " 的Cron表达式
这个函数首先创建了一个Date对象来表示传入的时间。然后,它根据repeatInterval参数的值来决定Cron表达式的哪些部分应该是具体的值,哪些部分应该是通配符(*或?)。最后,它将各个部分组合成一个Cron表达式字符串并返回。
注意,Cron表达式的最后一个字段(星期几)在大多数Cron实现中是可选的,并且可以用?来表示“不指定”。在这个函数中,如果repeatInterval不是“周”,那么星期几字段就被设置为?。同样,Cron表达式不包含年份字段,因此这个函数也不处理年份。