How to quit a java program at a specific time

余生颓废 提交于 2019-12-09 04:23:21

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

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.

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

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.

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