THpubs
THpubs

Reputation: 8172

In Rails how to schedule a task to check some database values and send reminder emails?

I need my system to calculate whether a Member's Membership is close to expiring every day and send an email to them. How can I do this?

For example, if I use the Clockwork gem how to do this? Its a bit unclear to me. How can we access the models through the Clockwork? How can we use it with Rails? I think the read me tells how to use it in pure Ruby. Please help. Im new. And how t make sure the scheduler is running?

Upvotes: 0

Views: 1012

Answers (3)

pdoherty926
pdoherty926

Reputation: 10379

Have you considered Sidekiq?

You could do something like this:

# app/workers/membership_worker.rb
class MembershipWorker
  include Sidekiq::Worker

  def perform(account_id)
    account = Account.find(account_id)
    message = "You have #{account.days_remaining}"
    # send reminder email
    # MembershipWorker.perform_in(1.day, account.id)
  end
end

# app/models/membership.rb
after_create ->{ MembershipWorker.perform_in(10.days, self.id) }      

Upvotes: 1

Simone Carletti
Simone Carletti

Reputation: 176472

You can use clockwork as long as you include the Rails environment in the configuration file.

For example, you can create a file in your Rails app config/clock.rb

require_relative 'boot'
require_relative 'environment'
require 'clockwork'

module Clockwork
  every(1.day, 'deliver-email', at: '00:00') {
    YourMailer.email(...).deliver
  }
end

This is mentioned in the QuickStart and Use with Queueing.

Alternatively, you can use the whenever gem.

I've been using both, but I now then to prefer the clockwork approach. Just keep in mind that clockwork counts starting from when the process is started. So if you restart the process 10 times, the email will likely to be sent 10 times. Make sure to check the email is not sent multiple times (the way you normally do it is by keeping a delivery log).

Upvotes: 0

deepthi
deepthi

Reputation: 685

Try using whenever gem It allows you to execute rake tasks. U can refer your model from the rake task.

Upvotes: 0

Related Questions