Schedule Rails Task to run at a certain time

后端 未结 1 1610
灰色年华
灰色年华 2021-02-20 11:21

I\'m currently creating a rails application and would like to find out how to schedule certain tasks to run at a specific time.

For e.g. An admin would want to send ema

1条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-20 11:44

    My preferred solution here is the Whenever gem.

    With it, you have schedule.rb file, which specifies when certain things should be done, including running rake tasks, executing methods, or even executing arbitrary shell commands:

    Example schedule.rb file, shamelessly copied from the Whenever readme:

    every 3.hours do
      runner "MyModel.some_process"
      rake "my:rake:task"
      command "/usr/bin/my_great_command"
    end
    
    every 1.day, :at => '4:30 am' do
      runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
    end
    
    every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
      runner "SomeModel.ladeeda"
    end
    
    every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday
      runner "Task.do_something_great"
    end
    
    every '0 0 27-31 * *' do
      command "echo 'you can use raw cron syntax too'"
    end
    
    # run this task only on servers with the :app role in Capistrano
    # see Capistrano roles section below
    every :day, :at => '12:20am', :roles => [:app] do
      rake "app_server:task"
    end
    

    I use Whenever for a number of tasks, including sending daily emails.

    0 讨论(0)
提交回复
热议问题