ryanpback
ryanpback

Reputation: 285

How to call methods dynamically based on time

I am creating an automatic raffling system. I have a draw button that will run a draw function to select a winner or winners and it sends an email to the admin.

I want this to be a completely automated system so that the admin only has to create the raffles and they receive an email with who won after the draw date has passed. My raffles have a draw date associated with them and once that passes, I need the function to be called.

How do I tell the application to check the time/date to see if any of the raffle draw times have passed? I have looked everywhere and cannot seem to find a way to do it.

Upvotes: 1

Views: 534

Answers (3)

AlexeyKuznetsov
AlexeyKuznetsov

Reputation: 412

You should write a rake task and add it's execution to your crontab on server. You can use whenever gem to simplify crontab scripting and auto update on each deploy (whenever-capistrano/whenever-mina). Example of your rake task:

namespace :raffle do

  task :check do
    Raffle.get_winners.each do |w| 
      Mailer.send_win_mail(w).deliver_later  
    end
  end

end

deliver_later is background execution in queue by the queue driver you use (DelayedJob/Rescue/Backburner etc)

Upvotes: 1

Cjmarkham
Cjmarkham

Reputation: 9681

I use Clockwork in my rails apps whenever I need to schedule things. Simply set it up to run a job when you want and do your logic within that job to see which raffles need to be processed. Example:

Clockwork config

every(1.day, 'Raffle::CheckJob', at: '01:00')

Job

Raffle.not_complete.find_each(batch_size: 10) do |raffle|
  if raffle.has_ended?
    // logic
  end
end

Upvotes: 2

Brian
Brian

Reputation: 5491

You could use the whenever gem to define a job that runs hourly (or however often you want), checks the draw dates, and runs the draw for any that have passed.

Upvotes: 2

Related Questions