IMAP闲置如何工作? [英] How IMAP idle works?

查看:147
本文介绍了IMAP闲置如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正试图在heroku上使用后台工作来实现它。任何想法?

解决方案

在Ruby 2.0和更高版本中,有一个空闲方法接受一个代码块,每当你得到未标记的回应。一旦你得到了这个回应,你就需要分手并取出进来的电子邮件。闲置呼叫也是阻塞的,所以如果你想保持它的异步,你需要在一个线程中做到这一点。



下面是一个示例(在这种情况下,@mailbox是Net :: IMAP的一个实例):

  def start_listener()
@idler_thread = Thread.new do
#永远运行它。完成后可以杀死线程。如果它检测到此线程终止
循环做
开始
@ mailbox.select(INBOX)
@mailbox,IMAP lib会为您发送
#DONE。空闲do | resp |
#你会从服务器获得所有的东西。对于新的电子邮件,只有
#对EXISTS感兴趣
,如果resp.kind_of?(Net :: IMAP :: UntaggedResponse)和resp.name ==EXISTS
# 。发送完成。这让你摆脱了封锁电话
@ mailbox.idle_done
end
end
#我们出去了,这意味着有一些电子邮件已经准备好了。
#去做UNSEEN的网站并获取它们。
process_emails()
rescue Net :: IMAP :: Error => imap_err
#套接字可能超时
rescue Exception => gen_err
putsSomething terrible wrong terre:#{e.messsage}
end
end
end
end


Can someone explain to me how IMAP IDLE works? Does it fork a new process for each connection that it opens? Can I somehow use eventmachine with it?

I am trying to implement it in ruby on heroku with background workers. Any thoughts?

解决方案

In Ruby 2.0 and up, there's an idle method that accepts a code block that will be called every time you get an untagged response. Once you got this response, you need to break out and pull the emails that came in. The idle call is also blocking, so you need to do this in a thread if you want to keep it asynchronous.

Here's a sample (@mailbox is an instance of Net::IMAP in this case):

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闲置如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆