本文介绍了如何在特定时间退出Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JMS侦听器应用程序,并且QueueReceive类实现了MessageListener.主要功能如下:

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();
    }

是否可以通过jms消息在程序中的特定时间退出应用程序?

Is there any way to quit the app at a specific time within the program not by way of the jms Message?

推荐答案

您可以使用 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();
}
}

这篇关于如何在特定时间退出Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 14:40