svz
svz

Reputation: 4588

Rails: send mail after some time has passed

I have the following scenario:
1. Someone creates a task in Redmine
2. Certain things are done (or not done) with this task
3. In case 3 days have passed since task creation and it is not in the right state, send an email to interested persons.

My question is how do I schedule an email (or the task that will check if an email is required) in exactly three days with Rails? The only option I could think of so far is to create some rake task and run it every couple of minutes. Are there better options?

Upvotes: 2

Views: 813

Answers (3)

Shadwell
Shadwell

Reputation: 34774

You've got a couple of options. You probably want to look at Active Job (Rails > 4.2). This lets you schedule a job to run after a specified period:

MyJob.set(wait_until: Time.now + 3.days).perform_later(record)

If you're on a version of rails prior to 4.2 then DelayedJob or Sidekiq or Resque could be used. Active Job is essentially a layer over the top of something like this anyway so a later migration to that shouldn't be too painful.

Alternatively if you don't need to check after exactly 3 days then you could sweep for tasks that need to have emails generated using cron (whenever is a good wrapper for this). You can sweep as often as you want, although every few minutes is probably excessive, and it means you won't have to set up a queueing back end on your server.

It does mean that you'll have to find the tasks that need emails generated for them whereas with the queuing system you'll know exactly which task you're dealing with already. However, it seems like plenty of those tasks won't need an email anyway so it might be more efficient to actively look for the ones that do.

Upvotes: 2

Milind
Milind

Reputation: 5112

You can use Whenever to schedule jobs/tasks/method calls ..almost anything

JUST add the gem ...run bundle install..add your code ....update the schedule.rb

for example:

##in schedule.rb
every 5.minutes do
    p "============Running rake task Only"
    rake "events:notify_user"
end

 every 2.hours do   
    p "============Running rake task and local script as well as calling a method from your code"
   command "/usr/bin/some_great_command"
   runner "MyModel.some_method"
   rake "some:great:rake:task"
 end

You can also watch the Railscasts

Upvotes: 0

Tom
Tom

Reputation: 520

As an alternative you can use https://github.com/resque/resque and https://github.com/zapnap/resque_mailer

Hope this helps.

Upvotes: 0

Related Questions