有人可以向我解释 IMAP IDLE 的工作原理吗?它是否为它打开的每个连接创建一个新进程?我可以以某种方式使用 eventmachine 吗?
我正在尝试用后台工作人员在 heroku 上的 ruby 中实现它。有什么想法吗?
有人可以向我解释 IMAP IDLE 的工作原理吗?它是否为它打开的每个连接创建一个新进程?我可以以某种方式使用 eventmachine 吗?
我正在尝试用后台工作人员在 heroku 上的 ruby 中实现它。有什么想法吗?
在 Ruby 2.0 及更高版本中,有一个 idle 方法接受一个代码块,每次收到未标记的响应时都会调用该代码块。收到此响应后,您需要中断并拉取进来的电子邮件。空闲调用也是阻塞的,因此如果要使其保持异步,则需要在线程中执行此操作。
这是一个示例(在这种情况下,@mailbox 是 Net::IMAP 的一个实例):
def start_listener()
@idler_thread = Thread.new do
# Run this forever. You can kill the thread when you're done. IMAP lib will send the
# DONE for you if it detects this thread terminating
loop do
begin
@mailbox.select("INBOX")
@mailbox.idle do |resp|
# You'll get all the things from the server. For new emails you're only
# interested in EXISTS ones
if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
# Got something. Send DONE. This breaks you out of the blocking call
@mailbox.idle_done
end
end
# We're out, which means there are some emails ready for us.
# Go do a seach for UNSEEN and fetch them.
process_emails()
rescue Net::IMAP::Error => imap_err
# Socket probably timed out
rescue Exception => gen_err
puts "Something went terribly wrong: #{e.messsage}"
end
end
end
end
IMAP IDLE 是邮件服务器实现可以支持的一项功能,它允许实时通知。[维基百科]
IDLE 命令可以与任何 IMAP4 服务器实现一起使用,该实现将“IDLE”作为支持的能力之一返回给 CAPABILITY 命令。
当客户端准备好接受未经请求的邮箱更新消息时,从客户端向服务器发送 IDLE 命令。服务器使用继续(“+”)响应请求对 IDLE 命令的响应。IDLE 命令保持活动状态,直到客户端响应继续,并且只要 IDLE 命令处于活动状态,服务器现在可以随时发送未标记的 EXISTS、EXPUNGE 和其他消息。
IDLE 命令因收到来自客户端的“DONE”继续而终止;这样的响应满足服务器的继续请求。[...] 客户端不能在服务器等待 DONE 时发送命令,因为服务器将无法区分命令和延续。