I have an administrative task that I need to run once a day: I need
to iterate through each user in the User table in the database, do
some calculation involving some other models, and update each user
record in the database.
I am thinking about just doing it at the console (env=production).
But I don't want to type all the statements again each time I carry
out this task. Is there a way to put this in a script and just run
the script?
Eventually, I'd like to schedule the task to run automatically every
day, and have some sort of progress display when the task is run.
To answer your initial idea, .... Yes, you can create a script, using
the same calls you would make in console, and run them using ./script/
runner. I do this all the time for various scripting tasks for
projects. One of the great features of rails.
You could do something like:
###### create the script to perform the updates:
$ cat ./script/update_users.runnable
puts "begin updating users: env=#{RAILS_ENV}"
begin
User.transaction do
User.find(:all).each do |u|
# perform calcs, update u, .....
end
end
puts "done."
rescue Exception=>e
#....
end
###### to run it against your dev env for testing:
$ ./script/runner ./script/update_users.runnable
begin updating users: env=development
...
###### to run it against your prod env:
$ ./script/runner -e production ./script/update_users.runnable
begin updating users: env=production
...
As for scheduling the task, you could use cron (or the windows equiv
if running under windows) to run the script at some particular
scheduled time/interval.
As for progress, you can always add logging calls in your script (and
likely a command-line arg as to whether or not to show debug info to
stdout, like the puts call in example above), either to the env's
existing log, or depending on your needs/wants, to a separate log file
for the particular task at hand (ie ./log/
development_update_users.log ?), that you could check to see how the
process is going, how it went, errors encountered, etc.