现在的位置: 首页 > 综合 > 正文

Liunx Crontab 定时的逻辑

2018年09月07日 ⁄ 综合 ⁄ 共 1512字 ⁄ 字号 评论关闭

在做活动项目时需要对时间的限制 就写模仿 crontab  写了一个

#vi /etc/crontab

crontab task 格式

* * * * * user task
分 时 日 月 周 user task
字段  说明
1   分钟(00-59)
2   小时(02-24)
3   日期(01-31)
4   月份(01-12)
5   周几(0-6,0为周日)

# utf-8

# '* * * * *'     -> 分 时 日 月 周
# '* * * 1-3 *'   -> 分 时 日 月 周
# '* * * 1,2,3 *' -> 分 时 日 月 周
# 01-59 01-23, 01-31, 01-12, 0-6

# simple :  CrontabUtil.new("20 09 * 04 2").check_time?
# simple :  CrontabUtil.new("20,21,40 * 29 04 2").check_time?
# simple :  CrontabUtil.new("20-40 09 29 04 2").check_time?
# return :  boolean 
class CrontabUtil
  attr_accessor :date, :minute, :hour, :day, :month, :week

  def initialize(cron_str, date=nil)
    return nil if cron_str.blank?

    init_data(cron_str)

    @date = date || Time.now
  end

  def check_time?
    check_minute? && check_hour? && check_day? && check_month? && check_week?
  end

  def check_minute?
    relatively(@date.strftime("%M"), @minute)
  end

  def check_hour?
    relatively(@date.strftime("%H"), @hour)
  end

  def check_day?
    relatively(@date.strftime("%d"), @day)
  end

  def check_month?
    relatively(@date.strftime("%m"), @month)
  end

  def check_week?
    relatively(@date.strftime("%w"), @week)
  end

  private
    def init_data(cron_str)
      cron_arr = cron_str.to_s.split(' ')
      return if cron_arr.size < 5

      @minute = cron_arr[0]
      @hour   = cron_arr[1]
      @day    = cron_arr[2]
      @month  = cron_arr[3]
      @week   = cron_arr[4]
    end

    def relatively(num,arr_str)
      return true if arr_str == '*'

      # 1. ','
      if arr_str.index ','
        return arr_str.split(',').include? num
      end
      # 2. '-'
      if arr_str.index('-')
        return (arr_str.split('-')[0]..arr_str.split('-')[1]).include? num
      end

      # 0. Integer
      if is_integer?(arr_str)
        return arr_str == num
      end

      return true
    end

    def is_integer?(str)
      begin
        return str.to_i.is_a? Integer
      rescue Exception => e
        return false
      end
      false
    end
end


使用

CrontabUtil.new("32 * 14 7 1 *").check_time?

抱歉!评论已关闭.