theKindOfMe

October 16, 2010

Task Scheduling with Cron, RVM and Rails

Filed under: Uncategorized — Tags: , , , — yasi8h @ 4:00 am

I wanted to do something every hour in my rails app. Basically a scheduled task. So i looked around and there were some plugins. But i choose to go with plain old cron. This should be a very straight forward task. However there are some pitfalls to be aware of. Specially if you are using RVM which depends on some environmental variables that are set on the shell. I created a bash script that is called from corn as scheduled. If you do the same be sure to make the script executable. chmod +x your_script.sh

my crontab -e looks like this

# m h dom mon dow command
#task1
0,30 05-07 * * * /home/foobar/script task1
0,10,20,30,40,50 08-18 * * * /home/foobar/script task1
0,30 19-21 * * * /home/foobar/script task1
#task2
0,30 19-21 * * * /home/foobar/script task2
#clean up the logs # once a week every saturday, at 00:00 (midnight)
0 0 * * 6 /home/foobar/script task3

for clean code get the gist

I have scheduled three tasks here. I am calling the same script with different arguments.

The script.

Note the source statement in the beginning. This loads RVM. And i am using the rails runner to call the methods i want to. These are located in some model classes within my rails app. Using the runner is just one option, but there are many you can use. Take look at here for more information on this topic.
If you are interested in using a gem to do the scheduling for you. Take a look at this.
After writing this i found some more post on the net that shows some what more elegant and better ways of doing the same thing. I think you should definitely give them a read.
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: