Is there anyway I can exit a java program after a couple of seconds e.g. 5 seconds.
I know you can quit the java program using:
System.exit(0);
But I'm not sure whether the 0 stands for seconds since this code:
System.exit(10);
also exits instantly
Using an Interrupt Mechanism. Here, we'll use a separate thread to perform the long-running operations. The main thread will send an interrupt signal to the worker thread on timeout. If the worker thread is still alive, it'll catch the signal and stop its execution.
The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.
Thread. sleep(1000); This will sleep for one second until further execution. The time is in milliseconds or nanoseconds.
System.exit(0) specifies the exit error code of the program.
you can put it on a timer and schedule the task
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimedExit {
Timer timer = new Timer();
TimerTask exitApp = new TimerTask() {
public void run() {
System.exit(0);
}
};
public TimedExit() {
timer.schedule(exitApp, new Date(System.currentTimeMillis()+5*1000));
}
}
and then you can just called TimedExit()
You can invoke Thread.sleep()
just before you exit your program:
// Your code goes here.
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
// log the exception.
}
System.exit(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With