Liunx Crontab 定时的逻辑


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


# 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







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值