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?
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.
来源:https://stackoverflow.com/questions/6923928/how-to-quit-a-java-program-at-a-specific-time