Rails: whenever + delayed_job to optimize rake tasks? - ruby-on-rails

I use whenever to call rake tasks throughout the day, but each task launches a new Rails environment. How can I run tasks throughout the day without relaunching Rails for each job?
Here's what I came up with, would love to get some feedback on this...?
Refactor each rake task to instead be a method within the appropriate Model.
Use the delayed_job gem to assign low priority and ensure these methods run asynchronously.
Instruct whenever to call each Model.method instead of calling the rake task
Does this solution make sense? Will it help avoid launching a new Rails environment for each job? .. or is there a better way to do this?
--
Running Rails 3

You could certainly look into enqueuing delayed_jobs via cron, then having one long running delayed_job worker.
Then you could use whenever to help you create the delayed_job enqueuing methods. It's probably easiest to have whenever's cron output call a small wrapper script which loads active_record and delayed_job directly rather than your whole rails stack. http://snippets.aktagon.com/snippets/257-How-to-use-ActiveRecord-without-Rails
You might also like to look into clockwork.rb, which is a long-running process that would do the same thing you're using cron for (enqueuing delayed_jobs): http://rubydoc.info/gems/clockwork/0.2.3/frames
You could also just try using a requeuing strategy in your delayed_jobs: https://gist.github.com/704047

Lots of good solutions to this problem, the one I eventually ended up integrating is as such:
Moved my rake code to the appropriate models
Added controller/routing code for calling models methods from the browser
Configured cronjobs using the whenever gem to run command 'curl mywebsite.com/model#method'
I tried giving delayed_job a go but didn't like the idea of running another Rails instance. My methods are not too server intensive, and the above solution allows me to utilize the already-running Rails environment.

Comment this line from schedule.rb
require File.expand_path(File.dirname(__FILE__) + "/environment")
Instead load only required ruby files like models in your case.

Related

How to migrate .delay tasks from Sidekiq to Active Job

Given an existing rails app with background processes managed by Sidekiq.
How can I migrate calls such as:
Model.delay.some_action()
From Sidekiq's syntax to Active Job's back-end agnostic syntax?
Update:
#craig.karminsky has pointed out the well-written Sidekiq to Active Job Wiki Page. This page addresses mailers.
Old Sidekiq syntax:
MyMailer.delay.send_message()
Active Job syntax:
MyMailer.send_message().deliver_later
That's a good solution for mailers, but how can I migrate non-mailer calls to .delay such as:
NotAMailer.delay.do_something()
Mike Perham, the creator of Sidekiq, has a very good Wiki page up for just such a situation.
I've made a gem for that on top of activejob: https://github.com/cristianbica/activejob-perform_later/. However the gem isn't very tested and this pattern is not a good one. Having code through your application that gets executed delay it will make your app hard to maintain and trigger all kind of bugs

Calling rake task on web request

In my Rails app, the user can upload a file and then what I need to do is: when the file is uploaded I want to start a rake task, which parses the file and feeds all the tables in the database, and depending on how large is the file, it can take some time. I assume sth like >> system "rake task_name" in my controller will do the work.
However is it the best practice? Is it safe? Because in that way any user would be starting a rake process. In this Railcast they recommend running rake in background. What would be an alternative or the common practice?
I am using Rails 3.2, so I couldn't use Active Job. I used Sidekiq and worked fine.
Check a very helpful tutorial here

Automatically restarting a Rails app and running Rake tasks

I have a Rails application that pulls information from various internal APIs and stores in a local SQLite DB. My rails application is essentially a glorified UI on top of this data pulled from multiple APIs.
For reasons outside the scope of this question, it is not straightforward to simply update the information in the DB on a periodic basis by re-querying the API. I'm basically forced to recreate the DB from scratch.
In essence I want to do something like this every X hours -
Automatically shut down the rails application
Put up a maintenance page ("Sorry, we'll be back in a few mins")
Drop the db, recreate it, and re-migrate it (rake db:drop; rake db:create; rake db:migrate)
Run my custom rake task that populates the tables again (rake myApp:update)
Re-start the application
This brings up a few questions
How do I have the app restart automatically every X hours? Should I schedule this externally using a cron job? Is there a rails way I can accomplish this?
How do I display a maintenance page if the app is down? Again, is this also an external re-direct I need to manage?
Most importantly, is there a good way to drop the tables and recreate them or should I be using rake tasks? Is there a way to call rake tasks at startups? I guess I could create a .rb process under config/initalizers that would run at startup (but only when Rails.env == 'production')?
Thanks for the help!
Just create a Cron task that runs periodically. That Cron task starts a shell stript that just does all the step you would run manually.
There is a gem (https://github.com/biola/turnout) at helps with the maintainance page. It provides rake tasks like rake maintenance:start and rake maintenance:end.
I think it is not necessary to drop the tables. Usually it should be enough to just delete all records and then create new records. If you really have to drop the database, it might be faster to just restore the database schema from a structure dump.
There is not a 'rails way' to reload a rails app every so often, since starting and stopping a rails app is outside the context of the app itself. A cron job is a fine way to go.
Typically a web server is running "in front" of the rails app, apache or nginix are common. The maintenance page would need to be implemented on that level (since the rails app is down for a moment remember), something like a temporary change to the configs and a reload should suffice. Then when bringing that app back online, restore the config to point to the rails app and reload again.
Using the rake tasks you have is fine, set the environment variable RAILS_ENV=production so they hit the right sqlitedb file. Don't bother attempting to call the rake tasks at rails start up, call them from the script called by your cron job, and then start the app after that.

Calling Models from Config Files

I am writing a ruby scheduler - namely rufus-scheduler and there are commands i need to write in the initializers section inside the config folder to perform a task every 1 minute or so. I am trying to access a method from a module within this. So my code would look like
scheduler.every("1m") do
puts("HELLO #{Time.now}")
ModelName.methodname("WHAT ARE YOU DOING")
end
This somehow doesn't perform the necessary operation in the model. Also im not sure if this is the right way to do things - such as call a model inside a config file. Is there a better place to put this code in the Model? Or is calling a Model within config files perfectly good practice. I looked over the internet to see the usage of different types of files in ruby but couldn't find a proper material. Any help or guidance appreciated.
If you want to access models from stand-alone tasks the best way is to use the rails runner wrapper. For example, you'd call your script as:
rails runner call_model.rb
This loads in the Rails environment and then executes your script, eliminating the need to do that yourself. Models on their own will not work since they are lacking the context of Rails.
If that's not sufficient, you may need to load the Rails environment more directly by including config/environment.rb into your rufus-scheduler configuration.
It sounds like you actually want a real scheduled action of some sort. config files are for configuration, not for actual working code of that sort.
There are tons of ways to run scheduled tasks in rails.
google "rails daemons" or "rails scheduled tasks" to start you off.
Here's a good list of scheduled-task best practices using cron:
A cron job for rails: best practices?

Rails - Is it okay (or possible) to run rake inside a controller?

I am using the sitemap_generator gem to build an xml sitemap. From the readme:
... run rake sitemap:refresh as needed to create/rebuild your Sitemap files
I'd prefer to do this any time the create action is ran in my Content controller. Is there a best practice for doing something like this?
It is possible, yes. But I would not recommend it. Rake tasks tend to take at least a few seconds to run which will occupy a server request and prolong the response to the client.
If you want to refresh the sitemap after every create, then I would recommend one of two solutions. Either analyse what the rake task sitemap:refresh does and use the code directly from your controller. But I would only do that as long as it doesn't take too much time to run and since I do not know much about sitemap_generator, I can't tell.
The other option would be to run the rake task from a delayed_job which I found to be the preferred alternative. That way, you can trigger the job from your create action but you don't have to wait for it to finish.

Resources