I want to make a rails app that displays accumulated data from
activerecord when a user loads the web page.
To accumulate the data I want to have a background task that goes out
every 5 minutes (roughly) and gets the data and then stores it in
activerecord. How can I have rails start this background process when I
start the rails app?
You can implement a rake task that builds the data and initiate the task
using CRON.
However, it really depends on what your idea of accumulated data is to
be honest. If a user is hitting your web page you can create an action
that instantiates the loading and updates a database. Or, if the data
is something that is being accumulated through creations or updates,
then you can use callbacks in your model to perform actions.
What type of data are you trying to accumulate?
Here's a brief example of something I created to tag when a person hits
a view in my app:
class ApplicationController < ActionController::Base
You can implement a rake task that builds the data and initiate the task
using CRON.
"However, it really depends on what your idea of accumulated data is to
be honest. "
The data is environmental. I want to be able to take a reading of
temperature, humidity and pressure at regular intervals. The interval
could be minutes or seconds.
I'm not sure it even has to be part of the rails app. It just has to
update activerecord. What I was hoping was that there was a way to start
this process at the same time as the rails app. I guess I could have a
startup script that starts both.
What I usually do in cases like yours is that I'll create a runnable
script that is run using rails runner (like $ ./script/rails runner -e
production ./script/fetch_save_foo.runnable), and then use cron to run
that script on some ongoing basis (where I typically have a crontab
per project where all cron'd events related to that project are kept).
The ability to easily develop/test/run scripts using your existing
app's models/etc via runner (using the same exact calls you would/
could make in console) is one of the nicest built-in features of
rails.