It is very easy to create a custom rake task in rails. We can often use this feature to ease our daily work. Recently I needed to run a cron job for a rails project, which is the perfect place for a custom rake task. You can follow these process to create a task.
1. Create a rake file as your_tasks.rake and put it in project_path\lib\tasks\
rails detects task from project_path\lib\tasks\
2. A sample rake task
task :start do #do some magic and start the cron end task :stop do #do some more magic and stop IT end
3. Now run in command prompt from the project folder as
rake start
To make your tasks more meaningful you might want to try giving namespaces and a little description which explains the task a bit.
Here the simple modification you need
Rake task
namespace :cron do desc "Starts cron job" task :start do #do some magic and start the cron end desc "Stops cron job" task :stop do #do some more magic and stop IT end end
Calling tasks
rake cron:start
Rake gives us the flexibility of defining dependent tasks so that the dependent tasks can be executed first.
Often we may need our rails environment to load before we do any thing. You can do it by
namespace :cron do desc "Starts cron job" task(:start => :environment)do #do some magic and start the cron end desc "Stops cron job" task(:stop => :environment)do #do some more magic and stop IT end end
Now when you will run the task, you will find that your environment is now loaded.
Resource:
http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial
2 comments:
Nice post ... ashraf..
really helpful.
Interesting way to ease Rails further!
Post a Comment