1

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?

4

4 回答 4

3

为此,您可以使用TimerTask [示例代码]。

例子:

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ExitOn {
Timer timer = new Timer();
TimerTask exitApp = new TimerTask() {
    @Override
    public void run() {
        System.exit(0);
    }
};
public ExitOn() {
timer.schedule(exitApp, new Date(System.currentTimeMillis()+5*1000));//Exits after 5sec of starting the app
while(true)
    System.out.println("hello");
}

public static void main(String[] args) {
    new ExitOn();
}
}
于 2011-08-03T09:01:06.393 回答
1

如果我们谈论 JMS,那么实现的类MessageListener将有一个方法onMessage,当任何消息进入队列时都会调用该方法。您可以实现此方法,以便它可以检查传入消息并quit()在特定条件下调用该方法。

我认为,我们不需要这里的 while 循环来不断检查退出你的QueueReceive.

于 2011-08-03T09:04:23.587 回答
1

使用 java.util.Timer(不是 javax.swing 中的那个!)

    boolean daemon = true;
    Calendar cal = Calendar.getInstance();
    //cal.set() to whatever time you want
    Timer timer = new Timer(daemon);
    timer.schedule(new TimerTask() {
        public void run() {
            // Your action here
        }
    }, cal.getTime());
于 2011-08-03T09:10:23.767 回答
0

您可以按照@Emil 的建议使用 Timer Task,这仅适用于简单的场景,例如 x 分钟或几小时后退出。

如果您需要更高级的调度,最好使用Quartz。使用石英,您可以提供一年中一个月的具体日期。基本上,您可以想象的任何可能的时间组合都可以使用石英进行配置。

于 2011-08-03T09:25:41.017 回答