如何在 Ruby on Rails 中的延迟作业完成后执行 ajax 回调?
我允许我网站上的用户旋转他们的照片。我通过 ajax 调用 Delayed_Job 进程(通过 Heroku)来旋转照片来完成此操作。他们按下“旋转照片”后,我会显示一个加载旋转器。但我的问题是:我的页面知道 Delayed_Job 何时完成以便我可以加载新照片的最佳方式是什么?
我是否需要对我的服务器进行连续的 ajax 轮询以确定延迟作业是否完成?或者有什么方法可以对我的页面实现 ajax 回调,以便在延迟作业完成时通知我的页面?
提前致谢。
I allow users on my site to rotate their photos. I accomplish this by an ajax call to a Delayed_Job process (via Heroku) that rotates the photo. After they press "rotate photo", I show a loading spinner. But my question is this: what is the best way for my page to know when the Delayed_Job is complete, so I can load the new photo?
Do I need to have a continuous ajax polling of my server to determine if the Delayed Job is complete? Or is there any way I can implement an ajax callback to my page that will notify my page when the Delayed Job has finished?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有很多方法可以处理这种事情。您可以像您提到的那样进行ajax轮询,您可以使用 comet 方法,其中您基本上保持连接打开,直到服务器上的任何操作完成为止,或者您甚至可以全力以赴并使用 网络套接字(不过对于这项任务来说可能有点过大了)。
如果没有套接字,当前就无法让服务器在没有客户端请求的情况下向客户端发送消息。
无论如何,您应该决定是否需要或想要将任务置于后台,以保证处理轮询/彗星/套接字的所有额外工作。旋转图像根本不会花很长时间。根据您是否有能力锁定服务器进程,在前台进行图像操作(而不是delayed_job)会简单得多。然后,当对该操作的 ajax 请求完成时,您就知道任务已完成。
There's a bunch of ways to deal with this kind of thing. You could do ajax polling as you've mentioned, you could use the comet approach where you essentially leave a connection open until whatever it is on the server has completed, or you could even go all out and use web sockets (probably a bit overkill for this task though).
Without sockets, there's currently no way to have your server send a message to the client, without the client requesting it.
In any case, you should decide whether the need or want to background the task warrants all the extra work of dealing with the polling/comet/sockets. Rotating an image shouldn't take long at all. Depending on whether you can afford to lock up a server process, it'd be a lot simpler to just do the image manipulation in the foreground (not delayed_job). Then, when the ajax request to that action has completed, you know the task is completed.