Create a file for the task:
# lib/tasks/delete_old_records.rake
namespace :delete do
desc 'Delete records older than 60 days'
task :old_records => :environment do
Model.where('created_at < ?', 60.days.ago).each do |model|
model.destroy
end
# or Model.delete_all('created_at < ?', 60.days.ago) if you don't need callbacks
end
end
Run with:
RAILS_ENV=production rake delete:old_records
Schedule it to run with cron (every day at 8am in this example):
0 8 * * * /bin/bash -l -c 'cd /my/project/releases/current && RAILS_ENV=production rake delete:old_records 2>&1'
You can also use the whenever gem to create and manage your crontab on deploys:
every 1.day, :at => '8:00 am' do
rake "delete:old_records"
end
Learn more about the gem on Github.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…