Method: Object#schedule_recurrence

Defined in:
lib/atome/extensions/atome.rb

#schedule_recurrence(name, target_time, recurrence, &block) ⇒ Object



808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
# File 'lib/atome/extensions/atome.rb', line 808

def schedule_recurrence(name, target_time, recurrence, &block)
  now = Time.now
  next_time = target_time

  case recurrence
  when :yearly
    next_time += 365 * 24 * 60 * 60 while next_time <= now
  when :monthly
    next_time = next_time >> 1 while next_time <= now
  when :weekly
    next_time += 7 * 24 * 60 * 60 while next_time <= now
  when :daily
    next_time += 24 * 60 * 60 while next_time <= now
  when :hourly
    next_time += 60 * 60 while next_time <= now
  when :minutely
    next_time += 60 while next_time <= now
  when :secondly
    next_time += 1 while next_time <= now
  when Hash
    if recurrence[:weekly]
      wday = recurrence[:weekly]
      next_time += 7 * 24 * 60 * 60 while next_time <= now
      next_time += 24 * 60 * 60 until next_time.wday == wday
    elsif recurrence[:monthly]
      week_of_month = recurrence[:monthly][:week]
      wday = recurrence[:monthly][:wday]
      while next_time <= now
        next_month = next_time >> 1
        next_time = Time.new(next_month.year, next_month.month, 1, target_time.hour, target_time.min, target_time.sec)
        next_time += 24 * 60 * 60 while next_time.wday != wday
        next_time += (week_of_month - 1) * 7 * 24 * 60 * 60
      end
    end
  else
    puts "Invalid recurrence option"
    return
  end

  seconds_until_next = next_time - Time.now
  wait_task = wait(seconds_until_next) do
    block.call
    schedule_recurrence(name, next_time, recurrence, &block)
  end
  store_task(name, { wait: wait_task, target_time: next_time, recurrence: recurrence })
end