js 生成linux的cron表达式

linux的crontab任务配置基本格式:

*   *  *  *  *  command

分钟(0-59) 小时(0-23) 日期(1-31) 月份(1-12) 星期(0-6,0代表星期天)  命令

校验是否正确:http://cron.schlitt.info/index.php?cron=30+7+*+*+*&iterations=100&test=Test

解析成cron表达式:

 // 循环条件转成cron表达式
      dateChangeCron (dates) {
        let m = ''
        let h = ''
        let w = dates.wloopValue || ''
        let mo = dates.mloopValue || ''
        if (dates.effectTime) {
          h = dates.effectTime.getHours()
          m = dates.effectTime.getMinutes()
        }
        let loopType = dates.loopType // 获取的参数,即循环方式
        var cron = ''
        if (loopType === 'DAILY') { //天循环
          cron = m + ' ' + h + ' * * *'
        } else if (loopType === 'WEEKLY') { // 星期天为0,星期6为6,周循环
          cron = m + ' ' + h + ' * * ' + w.join(',')
        } else if (loopType === 'MONTHLY') { // 1-31,月循环
          cron = m + ' ' + h + ' ' + mo.join(',') + ' * *'
        }
        return cron
      }

反解析cron表达式(将cron表达式解析成日期):

// 1 7 * * *
// 1 7 * * 1,2,4,0
// 1 7 1,16,30 * *
let cronChangeDate = str => {
  var toDate = {}
  if (!str) {
    toDate.loopType = '单次循环' //空的为单次,即不循环
  } else {
    var result = str.split(' ').join('')
    var count = 0 // *的个数
    result.replace(/\*/g, function (m, i) { // '*'需要转义
      if (m === '*') {
        count++
      }
    })
    var nArr = str.split(' ')
    var strLast = str.charAt(str.length - 1)
    if (count > 2) { // *的数量为3则为按天循环
      toDate.loopType = '天循环'
    } else if (strLast === '*' && count === 2) { // 最后一个为*则为按月循环
      toDate.loopType = '月循环'
      var mot = []
      var mkeys = nArr[2].split(',')
      for (var i = 0; i < mkeys.length; i++) {
        let mo = mkeys[i] + '号'
        mot.push(mo)
      }
      toDate.loopValue = mot.join(',')
    } else {
      toDate.loopType = '周循环'
      var keys = nArr[4]
      var en2cnMap = { //跟java的星期对应不一样,java的对应为1-7对应周天-周六
        0: '周天',
        1: '周一',
        2: '周二',
        3: '周三',
        4: '周四',
        5: '周五',
        6: '周六'
      }
      if (keys) {
        var cnKeys = keys.split(',').map(function (key, idx) {
          return en2cnMap[key];
        })
        toDate.loopValue = cnKeys.join(',')
      }
    }
    toDate.loopTime = nArr[1] + ':' + nArr[0]
  }
  return toDate //返回一个对象,根据需要解析成想要的样子
}


猜你喜欢

转载自blog.csdn.net/wh13267207590/article/details/80762440