How to quit a java program at a specific time

淺唱寂寞╮ 提交于 2019-12-08 06:15:32

问题


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?


回答1:


You can use TimerTask [Sample Code] for this purpose.

Example:

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



回答2:


If we talk about JMS, then the class implementing MessageListener will have a method onMessage, 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 the quit() method on specific condition.

I think, we don't need the while loop here for constantly checking for quitting your QueueReceive.




回答3:


Use java.util.Timer (not the one in 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());



回答4:


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.



来源:https://stackoverflow.com/questions/6923928/how-to-quit-a-java-program-at-a-specific-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!