每当带有Rails的Heroku中的计划任务时

use*_*629 4 ruby-on-rails heroku whenever ruby-on-rails-4

我需要在Heroku中运行计划任务.我在Rails的第一个cron工作!:-)

它在本地工作正常,但你如何使它在Heroku中工作?

我试过这个:heroku运行--update-crontab存储

但...

[失败]无法写crontab; 尝试运行`when',没有选项,以确保您的计划文件有效.

我还在Heroku的应用程序中添加了Heroku Scheduler.

这是我的config/schedule.rb

RAILS_ROOT = File.dirname(__FILE__) + '/..'
require File.expand_path(File.dirname(__FILE__) + "/environment")


every :day, :at => "11:00am" do
  @appointments = Appointment.where('date between ? and ?', Date.today, Date.today + 2.day)
  @appointments.each do |appointment|

    @emails = []

    @informated_people = InformatedPerson.where(person_id: appointment.person_id)
    @users = User.find(Authorization.where(:person_id => appointment.person_id).pluck(:user_id))
    @person = Person.find(appointment.person_id)

    @emails << @person.email

    @informated_people.each do |informated_person|
        @emails << informated_person.email
    end

    @users.each do |user|
        @emails << user.email
    end

    UserEmail.appointment_reminder_email(@emails.uniq, @person , 'Cita para el día ' + appointment.date.strftime("%d/%m/%Y %H:%M") + ' con el doctor ' + appointment.doctor + ' para la especialidad ' + appointment.specialty + ' en el centro ' + appointment.center + '.' ).deliver

  end
end
Run Code Online (Sandbox Code Playgroud)

小智 7

Heroku为这些任务提供调度程序(https://devcenter.heroku.com/articles/scheduler)

Scheduler是一个附加组件,用于按预定的时间间隔在应用程序上运行作业,就像传统服务器环境中的cron一样.

我建议您将此代码移动到约会模型中的函数.

def appointments_reminder
  @appointments = Appointment.where('date between ? and ?', Date.today, Date.today + 2.day)
  @appointments.each do |appointment|

  @emails = []

  @informated_people = InformatedPerson.where(person_id: appointment.person_id)
  @users = User.find(Authorization.where(:person_id => appointment.person_id).pluck(:user_id))
  @person = Person.find(appointment.person_id)

  @emails << @person.email

  @informated_people.each do |informated_person|
      @emails << informated_person.email
  end

  @users.each do |user|
      @emails << user.email
  end

  UserEmail.appointment_reminder_email(@emails.uniq, @person , 'Cita para el día ' + appointment.date.strftime("%d/%m/%Y %H:%M") + ' con el doctor ' + appointment.doctor + ' para la especialidad ' + appointment.specialty + ' en el centro ' + appointment.center + '.' ).deliver
end
Run Code Online (Sandbox Code Playgroud)

接下来,您需要创建该lib/tasks/scheduler.rake文件

desc "Heroku scheduler tasks"
task :email_appointments_reminder => :environment do
  puts "Sending out email reminders for appointments."
  Appointment.appointments_reminder
  puts "Emails sent!"
end
Run Code Online (Sandbox Code Playgroud)

最后,使用Web界面,您可以使用任务名称安排它.在这个示例中rake email_appointments_reminder,您可以从下拉选项中选择频率,以便在每天上午11:00运行它.

我还建议在使用此控制台命令安排任务之前手动测试该任务: heroku run rake email_appointments_reminder