idel使用方法java_JavaMail:保持IMAPFolder.idle()存活

一个常见的错误是假设IDLE命令将不间断地发布更新.然而,定义IDLE扩展的

RFC 2177表示:

The server MAY consider a client inactive if it has an IDLE command

running, and if such a server has an inactivity timeout it MAY log

the client off implicitly at the end of its timeout period. Because

of that, clients using IDLE are advised to terminate the IDLE and

re-issue it at least every 29 minutes to avoid being logged off.

This still allows a client to receive immediate mailbox updates even

though it need only “poll” at half hour intervals.

特别是GMail,如你所说,大约10分钟,有一个低得多的超时时间.

我们只需要每9分钟左右重新发行一次IDLE命令,让它工作. javax.mail API无法为IDLE命令设置超时,因此您将需要一个第二个线程来移动此操作.

第一种方法是让第二个线程中断第一个线程,处理异常并忽略它.然而,这将允许没有干净的方式来关闭线程,所以我不会推荐它.一个更清洁的方法是让第二个线程向服务器发出一个NOOP命令.这完全没有,但是足够让IDLE中止并重新发行.

我在这里提供一些代码来做到这一点:

public void startListening(IMAPFolder imapFolder) {

// We need to create a new thread to keep alive the connection

Thread t = new Thread(

new KeepAliveRunnable(imapFolder), "IdleConnectionKeepAlive"

);

t.start();

while (!Thread.interrupted()) {

LOGGER.debug("Starting IDLE");

try {

imapFolder.idle();

} catch (MessagingException e) {

LOGGER.warn("Messaging exception during IDLE", e);

throw new RuntimeException(e);

}

}

// Shutdown keep alive thread

if (t.isAlive()) {

t.interrupt();

}

}

/**

* Runnable used to keep alive the connection to the IMAP server

*

* @author Juan Martín Sotuyo Dodero

*/

private static class KeepAliveRunnable implements Runnable {

private static final long KEEP_ALIVE_FREQ = 300000; // 5 minutes

private IMAPFolder folder;

public KeepAliveRunnable(IMAPFolder folder) {

this.folder = folder;

}

@Override

public void run() {

while (!Thread.interrupted()) {

try {

Thread.sleep(KEEP_ALIVE_FREQ);

// Perform a NOOP just to keep alive the connection

LOGGER.debug("Performing a NOOP to keep alvie the connection");

folder.doCommand(new IMAPFolder.ProtocolCommand() {

public Object doCommand(IMAPProtocol p)

throws ProtocolException {

p.simpleCommand("NOOP", null);

return null;

}

});

} catch (InterruptedException e) {

// Ignore, just aborting the thread...

} catch (MessagingException e) {

// Shouldn't really happen...

LOGGER.warn("Unexpected exception while keeping alive the IDLE connection", e);

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值