Search code examples
ruby-on-railsrubybackgroundrake

Rails 3.2 - Rake Background Task Create DB Records


I want to create a rake task that will run automatically every seven days (sunday at midnight), that will analyse a weeks worth of data (at max 20,000 records per week).

An Outlet has_many :monitorings A Monitoring belongs_to :outlet

I want to check if at the end of the week an outlet has had a minimum of 4 records created. If not, I want a record to be created inside of the DB in a table called unmonitored.

The record should contain the the number of times it has been monitored and the week start and end dates.


Solution

  • To run a rake task periodically, you can use bare cron jobs or a nice ruby wrapper, Whenever.

    Take a look:

    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