如何在特定时间退出java程序
我有一个JMS侦听器应用程序,并且类QueueReceive实现了MessageListener。主要功能如下:
public static void main(String[] args) throws Exception {
InitialContext ic = getInitialContext();
QueueReceive qr = new QueueReceive();
qr.init(ic, QUEUE);
System.out.println("JMS Ready To Receive Messages (
To quit, send a \"quit\" message).");
// Wait until a "quit" message has been received.
synchronized(qr) {
while (! qr.quit) {
try {
qr.wait();
} catch (InterruptedException ie) {}
}
}
qr.close();
}
有没有什么方法可以在程序内的特定时间退出应用程序而不是通过jms消息?
I have a JMS listener app, and the class QueueReceive implements MessageListener.the main function as below:
public static void main(String[] args) throws Exception {
InitialContext ic = getInitialContext();
QueueReceive qr = new QueueReceive();
qr.init(ic, QUEUE);
System.out.println("JMS Ready To Receive Messages (
To quit, send a \"quit\" message).");
// Wait until a "quit" message has been received.
synchronized(qr) {
while (! qr.quit) {
try {
qr.wait();
} catch (InterruptedException ie) {}
}
}
qr.close();
}
Is there any way to quit the app at a specific time within the program not by way of the jms Message?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 TimerTask [示例代码]用于此目的。
示例:
You can use TimerTask [Sample Code] for this purpose.
Example:
如果我们谈论 JMS,那么实现
MessageListener
的类将有一个方法onMessage
,当任何消息进入队列时都会调用该方法。您可以实现此方法,以便它可以检查传入消息并在特定条件下调用quit()
方法。我认为,我们不需要这里的 while 循环来不断检查
QueueReceive
是否退出。If we talk about JMS, then the class implementing
MessageListener
will have a methodonMessage
, which will be called when any message enters the queue. You can implement this method such that it can check the incoming message and call thequit()
method on specific condition.I think, we don't need the while loop here for constantly checking for quitting your
QueueReceive
.使用 java.util.Timer (不是 javax.swing 中的那个!)
Use java.util.Timer (not the one in javax.swing!)
您可以按照@Emil的建议使用计时器任务,这仅适用于简单的场景,例如在x分钟或小时后退出。
如果您需要更高级的调度,最好使用 Quartz。使用 Quartz,您可以提供一年中一个月的具体日期。基本上,您可以想象的任何可能的时间组合都可以使用 Quartz 进行配置。
you can use Timer Task as @Emil suggested, this is only useful for simple scenarios like quit after x mins or hours.
if you need more advanced scheduling its best to use Quartz. Using Quartz you can provide the specific date of a month of a year.. basically any possible combination of times which you can imagine can be configured using quartz.