A Rails Fake Cron
Recently I've been working on a project on which a simple cron job was
not an option, while it would have been the perfect solution for the
task given. Since we were sure that we were not dealing with long
running jobs we decided that it could run during a user's request. But
not on every request, only every so often would be just fine.
A fake cron job is the solution I came up with... (it goes into the
ApplicationController)
before_filter :fake_cron_job
# checks on every request if the last check is
# older than one hour, if so, yields block
def fake_cron_job
periodic_check(:interval => 1.hour,
:path => '/tmp/project_name_fake_cron_check') do
# add tasks to perform periodically here...
Milestone.check_for_over_due!
end
end
def periodic_check(options)
defaults = {
:interval => 12.hours,
:path => File.join(Rails.root, 'tmp', 'periodic')
}
options.reverse_merge! defaults
path = options[:path]
return if File.exist?(path) and
Time.now - File.mtime(path) < options[:interval]
yield
FileUtils.touch(path)
end