Pabi
Pabi

Reputation: 994

Rails: Run a function that will generate a date and run another function at that date

I am looking for a way to make it so that when you run a function it will generate a random date between two defined dates, that will be stored somewhere, so that somehow the other function at that date could be run.

In short I need something that will execute a function at a defined date.

Please let me know if I wasn't clear enough.

Thank you.

Upvotes: 1

Views: 67

Answers (1)

EugZol
EugZol

Reputation: 6545

Well, good old rand should solve the problem:

require 'date'
first = Date.today
second = Date.parse '2018-08-08'
random = first + rand((second-first).to_i+1)

Some reference: random(i) will generate a random integer in [0..i-1] range (including first and last value). And Date + Integer gives new Date, given amount of days in future. Date - Date gives difference between Dates in days.

The second question is how do you run the task on specific date. Well, given you have many dates scheduled ahead (and not just one), it would be a good decision to use whenever gem. Just check every day what tasks are due and run them:

# config/schedule.rb
every 1.day do
  runner "Task.perform"
end

# app/models/task.rb
class Task < ActiveRecord::Base
  def self.perform
    self.where(date: Date.today).each do |task|
      # do what is needed to be done
    end
  end
end

So you schedule the Task by just saving it to the database: Task.create(date: ...), and then wait for Task.perform to perform it on the due date.

Upvotes: 1

Related Questions