我设置了一个rails API,我希望每隔3天(72小时)从一个数组中pop
。我有点迷失了如何迭代日期以正确选择我的数组。这就是我目前正在使用的内容。
def index
theme = ["Superhero", "Star-Wars", "Pokemon", "Other-Animals", "Hats", "Sports"]
current_theme = theme.shuffle.pop
start_time = DateTime.new(2017,5,9,00,00)
end_time = DateTime.new(2018,5,9,00,00)
start_time.upto(end_time) do |t|
cycle = t*3
while t = cycle do
render json: current_theme
// bad loop
end
end
end
答案 0 :(得分:1)
您可以使用Enumerator
中的.cycle
,.step
和.next
全部
require 'date'
start_time = DateTime.new(2017,5,9,00,00)
end_time = DateTime.new(2018,5,9,00,00)
# create an enumerator
theme = ["Superhero", "Star-Wars", "Pokemon", "Other-Animals", "Hats", "Sports"].cycle
# iterate using step over 3 days
start_time.step(end_time, 3) do |date|
puts "#{date} - #{theme.next}"
# Do something like this:
render json: theme if DateTime.now.beginning_of_day <= date + 2
end
# => 2017-05-09T00:00:00+00:00 - Superhero
# => 2017-05-12T00:00:00+00:00 - Star-Wars
# => 2017-05-15T00:00:00+00:00 - Pokemon
# => 2017-05-18T00:00:00+00:00 - Other-Animals
# => 2017-05-21T00:00:00+00:00 - Hats
# => 2017-05-24T00:00:00+00:00 - Sports
# => 2017-05-27T00:00:00+00:00 - Superhero
#...
同样DateTime.now.beginning_of_day
取决于ActiveSupport,但您可以轻松实现类似的内容,Date.today.to_datetime
等
答案 1 :(得分:0)
使用std::tuple
进行此类操作。 whenever是一个伟大的宝石,可以使用Ruby DSL创建和更新cronjob
。例如,您可以将任务编写为:
crontab