Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Share database with a daemon?
5 Posts
Share database with a daemon?

I have a web application, hosted on a cloud, which communicates with embedded hardware over the internet. Its data persistence is handled via a SQLITE3 database in the cloud. I need to add some logic which will be timer-based, and it doesn't rationalize well with a webapp architecture...so I presume that I will write a daemon that will always be out there, sleeping until the next event, or polling for asynchronous conditions.

However, I am undecided as to the architecture for sharing DB access. Either the webapp and the daemon both need DB write access, which I fear will be overly complicated for my simple application, or I must offload all DB writing to the daemon and establish some type of a work queue from the webapp to the daemon.

It seems like this ought to be a fairly common need, and I don't want to reinvent the wheel. Any thoughts on what code/gems/etc I could use to get started?

Bill,

Have you considered writing a rake task for the timer-based process and then calling this rake task from a cron job?

Check out the whenever gem for writing cron jobs in Ruby.

http://railscasts.com/episodes/164-cron-in-ruby

Hope that helps?

"Gavin Morrice":htt://gavinmorrice.com

http://handyrailstips.com

Gavin,

I like the notion of a cron-based wakeup for a rake task... however it is the Database sharing that has me confused. Since I need to have write access from both the webapp and the daemon task, how can that be managed? I think that only one is allowed write access.

Thanks, Bill

Bill,

From the info you've given me I'd approach this as follows:

Create a module that handles the task you're running.

module MyModule

def method_to_run_code
  # ...
end

module_function :method_to_run_code

end

and then a rake task:

desc "This task will have access to all of your models etc in the correct environment" task :my_task => :environment do

MyModule.method_to_run_code

end

Then a cron that runs

rake my_task RAILS_ENV=production

Hopefully that makes sense and will work for you - if not, I should be around on Skype: gavin-morrice

Cheers

Gavin

Gavin is correct in this. Creating the module inside of your webapp will give it full access to your environment (and database) by using the credentials offered up in your database.yml for the production environment. Croning the rake task will allow that functionality to be called within the RAILS_ENV=production environment which gives it access to everything that the application running in production mode will, such as the production database user.

Nice answer Gavin!

5 Posts
Login to add your message