I am learning cron job and delayed job, and I want to send emails using background job; for that I'm using the delayed_job
gem. I don't want to start the worker manually by running the rake jobs:work
command, but I want to set this rake in cron job so whenever an user login into the dashboard this command is fired and a mail is sent to his address. Following is my code:
Sending mail method
def dashboard
@user = User.find(params[:id])
UserMailer.delay.initial_email(@user)
end
UserMailer
def initial_email(user)
@user = user
mail(:to => user.email,:subject => "Welcome to my website!")
end
For the cron job I am using "whenever" Gem, so what should I write in my schedule.rb file so that when I login into the dashboard I get a mail without running worker manually?
DelayedJob is supposed to be running all the time in the background so it doesn't need to be fired up. The worker agent checks the queue to see if any tasks need to be performed, and runs them. It's pretty much like a 2nd instance of your application that runs in the background checking for tasks that need to run.
So you should start the worker agent with
script/delayed_job start
and let it run all the time. You can use a separate tool like monit or god to monitoring your worker agent to make sure it is always running.