简体   繁体   中英

Using sidekiq in rails, how can I send messages to a bunch of users, each of which has a unique time they want to receive it?

Hey I have a rails application and a bunch of users and I want to send them a message once per day at a preferred local time of the user's choice. (A message is a text, email, or chatbot notification.)

I believe I could add something to my User model that would allow for something to be performed every 24 hours at the preferred time but I'm not sure specifically how to implement that AND I also don't know how to remove these jobs from the queue if, for example, the user changes their preferred time or they want to disable messages all together.

Any thoughts on how I could do this?

Where is your application hosted? You can have a cron task or a scheduler (Heroku) that runs every hour (or every 10 minutes). It would query in a users preferences table searching for users who want to receive the email at this moment (or in a range near this moment, such as the next 10 minutes).

time = Time.now
@users = User.include(:settings).where(“settings.receive_email_at between ? and ?”, time, time + 10.minutes)

You may need some changes to handle timezones and to avoid sending duplicate emails, but that's just an idea.

It's simple. Build two models - One to store user and its time mapping ( UserTimeMapping ) and the second one to create a unique entry for each day when a message is sent to user ( UserMessage ).

Write a cron task which runs every 10 minutes and pulls all the records from UserTimeMapping which are to be executed for next 10 minutes and schedules a worker task for the exact time (say MessageTriggerWorker ). The worker has to check in UserMessage table whether a record exists for the given user_id for today and if yes it has to return without performing any task. If that is not the case then it should send the message and create a record in the UserMessage table.

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