简体   繁体   中英

How do you write a Rails cron job Whenever gem?

The whenever gem is installed. I see all kinds of cron and whenever tutorials about scheduling tasks with minutes, hours, days etc. I watched the railscast video on cron/ whenever . But I've yet to find any examples about how to write a job itself, other than rake tasks.

I want to schedule a task that checks the database for changes. The idea is that the database will have tags that tell you which particular row has changed. Whenever should poll the database periodically to check for these changes. Then it hopefully can push, or let the client know it needs to update the page dynamically using ajax. If I were doing this manually, I'd use commands like:

 rails dbconsole
 select blah from blah;

Is there a way to write mysql commands in whenever ? Is this the correct/best way to poll the database for changes? I know there are ways to poll a database from mysql itself, but I've been specifically told to do it from the rails side.

I'm a newbie to all of these technologies (Rails, databases, ajax) so that's probably why the answer isn't clear to me.

On the client end, I have buttons that use jquery to add/delete/change row data, just to assure myself I know how to change things in the table once I can get stuff from the database. Those buttons will eventually be removed.

Right now, the page uses ajax to refresh the entire html table. But they would like just a row refresh/update through ajax.

Look at the RailsCast for cron/whenever again. You'll notice an example line of code like this:

runner "MyModel.some_process"

The code in the strings is evaluated and run. So whatever you want whenever to run, just write that code yourself and have a way for it to be called.

So maybe you create a class named DatabaseWatcher and store it in lib which has a class level method named .run , you'd do the following:

runner "DatabaseWatcher.run"

And that's it. In your .run method is where you'd put your logic. As for how to actually write that code, that depends on your requirements. Are you looking for if the updated_at time is within 1 minute of now? Do you store a time when you last checked the DB, and then you can see if the updated_at time is greater than that? Do you have a table that stores every time the model is changed? That all depends on you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM