IMAP闲置如何工作?

Abh*_*ena 4 ruby imap heroku eventmachine

有人可以向我解释IMAP IDLE的工作原理吗?它为每个打开的连接分配一个新进程吗?我可以以某种方式使用eventmachine吗?

我正在尝试用背景工作者在heroku上的ruby中实现它.有什么想法吗?

小智 7

在Ruby 2.0及更高版本中,有一个空闲方法接受每次获得无标记响应时都会调用的代码块.一旦得到这个响应,你需要突破并拉出进来的电子邮件.空闲调用也是阻塞的,所以你需要在一个线程中执行此操作,如果你想让它保持异步.

这是一个示例(在这种情况下,@ 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
Run Code Online (Sandbox Code Playgroud)