I want to create recurring events using the Ice Cube gem in Rails - my question is, how do I then correctly, or rather efficiently, use these recurring rules for triggering actual events?
An example of this would be a recurring invoice.
Say I have an Ice Cube recurrence set for once a week and I saved it to a recurring invoice row using to_yaml. I now have a row in the database with a serialized recurrence rule. The only way I can imagine using this is to run through each and every row in the database, unserializing the saved recurrence rules and checking whether it needs to run today with schedule.occurs_on?(Date.new) - this would then be put into a cronjob that runs daily:
items = RecurringItem.find(:all)
items.each do |item|
schedule = Schedule.from_yaml(item.schedule_yaml)
if schedule.occurs_on?(Date.new)
#if today is a recurrence, do stuff!
end
end
This looks terribly inefficient to me - but I might be doing it completely wrong. Is there no better way to use Ice Cube?
Ice Cube seems to specialize in setting up very complicated schedules (occurs on the 1st and 4th wednesdays, but only if they're even numbered days, and not if a weekend, etc.)
If that's what you need, then the task you described probably IS the most efficient way to run a number of tasks every day on that kind of complex schedule. If you don't need that complexity in your schedules, then you could look at something like whenever (as MatthewFord mentioned), which just uses cron schedules to setup tasks to be executed, but that's intended for admin-type tasks, and so requires a config file to be edited, and doesn't work if you need to be adding and removing things via your application interface.
Another option for using Ice Cube would be to have a monthly cron go through every schedule, and set up another table defining which events have to be run on which days for the next month. (each row has a date and a task definition), and your daily cron could select from that table...
You would also have to update that table for one month ahead of time every time one of the schedules changed in the application... kind of a hassle, so unless you have hundreds of thousands of schedules to look through once a day, it's probably not worth the trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With