gpt4 book ai didi

ruby-on-rails - 如何正确执行用户设置的时间/频率的重复性任务

转载 作者:IT王子 更新时间:2023-10-29 05:55:35 24 4
gpt4 key购买 nike

用户订阅包含最新视频的电子邮件,但他们也可以设置何时收到这些电子邮件。

Subscription(user_id, frequency, day, time, time_zone)

user_id | frequency | day | time | time_zone
1 | daily | null | 16:00 | GMT
2 | weekly | friday | 11:00 | UTC
3 | weekly | monday | 18:00 | EST

我们如何才能在用户选择的准确时间和频率下在他们的时区发送电子邮件而不会搞砸(例如发送双重电子邮件或错过时间)

唯一的频率是每日和每周,如果每日则日期为空。

我使用 Redis 作为数据库,让我知道如何以正确的方式做到这一点!

最佳答案

我将使用 resque-scheduler gem 扩展 fmendez 的答案.

首先,让我们创建发送电子邮件的 worker

class SubscriptionWorker
def self.perform(subscription_id)
subscription = Subscription.find subscription_id

# ....
# handle sending emails here
# ....

# Make sure that you don't have duplicate workers
Resque.remove_delayed(SubscriptionWorker, subscription_id)

# this actually calls this same worker but sets it up to work on the next
# sending time of the subscription. next_sending_time is a method that
# we implement in the subscription model.
Resque.enqueue_at(subscription.next_sending_time, SubscriptionWorker, subscription_id)
end
end

在您的订阅模型中,添加一个next_sending_time 方法来计算下一次发送电子邮件的时间。

# subscription.rb
def next_sending_time
parsed_time = Time.parse("#{time} #{time_zone}") + 1.day

if frequency == 'daily'
parsed_time
else
# this adds a day until the date matches the day in the subscription
while parsed_time.strftime("%A").downcase != day.downcase
parsed_time += 1.day
end
end
end

关于ruby-on-rails - 如何正确执行用户设置的时间/频率的重复性任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14964567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com