使用Javascript实现一个Cron表达式的函数

要实现一个函数,该函数接受时间和重复时间(日、周、月、年)作为参数,并返回一个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表达式不包含年份字段,因此这个函数也不处理年份。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值