user2200234
user2200234

Reputation:

How can I schedule a job on Heroku for a selected day day?

I have a Rails app deployed on Heroku with the Heroku scheduler add-on and followed the following link: Heroku Scheduler. What I am attempting to do is set the following the index to be ran on the 18th of every month. My index method looks like the following:

def index 
    @hospital_bookings = HospitalBooking.scoped
    hospital_booking = @hospital_bookings
    @user = current_user

    if params[:format] == "pdf"
      @hospital_bookings = @hospital_bookings.where(:day => Date.today.beginning_of_month..Date.today.end_of_month)
    end

    respond_to do |format|
      format.html
      format.pdf do
        render :pdf => "#{Date.today.strftime("%B")} Overtime Report",
               :header => {:html => {:template => 'layouts/pdf.html.erb'}}
        OvertimeMailer.overtime_pdf(@user, hospital_booking).deliver
      end
    end
  end

So that effectively when the rake task is ran on the 18th of every month this will fire my OvertimeMailer and email the user. I have currently in my in my scheduler.rake

task :overtime_report => :environment do
  if Date.today.??? # Date.today.wday == 5
  HospitalBooking.index
  end
end

I know the above rake task is wrong. But am trying to achieve something along these lines

Update

class OvertimeMailer < ActionMailer::Base

  default :from => DEFAULT_FROM

 def overtime_pdf(user, hospital_booking)
  @hospital_bookings = hospital_booking
  @user = user
  mail(:subject => "Overtime", :to => user.email) do |format|
    format.text # renders overtime_pdf.text.erb for body of email
    format.pdf do
      attachments["hospital_bookings.pdf"] = WickedPdf.new.pdf_from_string(
        render_to_string(:pdf => "overtime",:template => 'hospital_bookings/index.pdf.erb', :layouts => "pdf.html")
      )
    end
  end
end
end 

Upvotes: 2

Views: 248

Answers (1)

John Beynon
John Beynon

Reputation: 37507

Something simple like;

task :overtime_report => :environment do
  if Date.today.day == 18
    HospitalBooking.index
  end
end

and then run your scheduler everyday.

But you don't want to be calling your controller index method like this from your rake task. HospitalBooking will be the model and not the controller as you are expecting. Your best option is to put your email/generating PDF as a callable method in your model and then call that from your task.

Upvotes: 2

Related Questions