Reputation: 1
In Rails 5, I have this method in my "Aulas" ("Classes" in Portuguese) Controller:
def set_week_classes
classes = Aula.all.to_a
@this_week_classes = classes.shift(2)
end
Considering that "classes" is an array, I would like to have "@this_week_classes = classes.shift(2)" being executed every Monday, at midnight (Brazil's time), getting the next two items of the classes array to be shown on the view. And also, I would like that when it reached the end of the array, it simply started all over, making "@this_week_classes" become again the first two items of the classes array. How could I make this happen? Thank you!
Upvotes: 0
Views: 819
Reputation: 774
You can use sidekiq with some kind of a scheduling gem (like sidekiq-scheduler or sidekiq-cron). Depending on your installation you could also copy use a rake task and run it periodically using cron. If you use cloud then your provider definitely have some kind of scheduler available.
BTW all of your source code should probably be in English. Mixing some Portuguese class names doesn't look great and can be confusing for other contributors.
But if your only goal is to show some what classes are listed this week it's probably better to do sth like this:
classes = Aula.all.to_a # not the best for the memory
shift = DateTime.current.weeks_since(CONSTANT_TIME) % classes.size
@this_week_classes = ([classes]+[classes])[shift..(shift+2)] # [classes]+[classes] make sure that we won't get too little classes if we reach the and of the `classes` array
Upvotes: 1
Reputation: 56
It appears you ask two questions at the same time:
- Run a job every week at a certain time.
Rails offers different ways to do this. To me the best fit seems to work with an active job library.
Possibilities are:
Another open library for this type of task is the gem delayed_job
. It's not very performant but easy to include into small projects.
- Cycle through an array of items.
Here a possibility is instead of actually shifting the items out of your array that you store the job run in your database. Keep in mind there are other possibilities that do not need you to change your database. Following code is not tested but should be seen as pseudocode.
def run_job
last_aula_job = AulaJob.all.order(:created_at).last
classes = Aula.all.to_a
total = classes.count
p = last_aula_job.last_pointer % count
@this_week_classes = classes[p..p+1]
# do something with @this_week_classes
AulaJob.create(last_pointer: p + 2)
end
Upvotes: 0