Search code examples
rubyscheduled-tasksrake

Calling class method within rake task, nothing happening


So I have a class method which works great for my ApplicationMailer. It finds orders that are not fulfilled, converts them to CSV, attaches them in an email, and emails them to a predefined email address.

This is working fantastically.

However, when I call this method in a rake task, it does absolutely nothing. This is the first rake task I have written and am trying to use it with heroku scheduler to send out orders to be fulfilled every night.

the code for my rake task is below:

desc "send daily orders to shipping"
task :send_orders_to_shipping => :environment do
    ApplicationMailer.email_days_orders
end

This rake task shows up in rake -vT as rake send_orders_to_shipping but when I call "bundle exec rake send_orders_to_shipping", the command line seems to pause for 5-10 seconds, like its doing something, but no error is passed back or anything and nothing happens. No orders are marked as fulfilled in the database as they are when I simply run the class method from the command line and no emails are sent.

Any help is appreciated, I am new to rake and am wondering if I have missed something in my reading?

I was instructed to put the :environment block by herokus documentation for using the scheduler addon. Could this be messing things up?

edit: here is the code for ApplicationMailer.email_days_order which works from the command line.

def email_days_orders
    ordlength = Order.where(fulfilled: false).length
    indordlength = Individualorder.where(fulfilled: false).length

    if ordlength > 0
      attachments["school_orders_#{Date.today}.csv"] = Order.todays_orders_to_csv
    end

    if indordlength > 0
      attachments["individual_orders_#{Date.today}.csv"] = 
      Individualorder.todays_indorders_to_csv
    end

    if ordlength > 0 || indordlength > 0
      mail(to: [ENV['SHIPPING_EMAIL_1'], ENV['SHIPPING_EMAIL_2'], 
      ENV['SHIPPING_EMAIL_3']] ).deliver
    end

end

Solution

  • You're forgetting to actually send the email. Try ApplicationMailer.email_days_orders.deliver_later (or .deliver_now)