Senju
Senju

Reputation: 1035

Rails updating/modifying the view dynamically while using background jobs

Is there a way to update or modify the view from a background job? For example if a user wants to send 100 emails, I want to show the background job's progress to to the user through the view. Once the first email is sent, show 1/100, the second, 2/100, etc.

I don't know if it matters, but I am using delayed_job.

Upvotes: 0

Views: 475

Answers (1)

Cyril Lavedrine
Cyril Lavedrine

Reputation: 161

If you explicitly want the server to be the source of the page update, then you should look into actioncable, which is a Rails implementation of websockets (part of rails 5.0, available as a gem for previous versions)

The principle : The client subscribes to a channel SendMailChannel when the order to send the 100 mails is given. Whenever the job running on the server has sent a mail, it broadcasts this information to all subscribers through the SendMailChannel. You can then use this information in a coffee script to update the page and display the counter accordingly.

If your only intention is to update a counter, this might be a bit of an overkill, considering all the configuration that has to be done (development of jobs + channels + coffeescript actions for subscription and update + maybe changing your server to a threaded one like Puma).

An ajax update every 10 or so seconds would be more network-heavy and less efficient and versatile but way easier to implement.

Upvotes: 4

Related Questions