Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Java program exit after a couple of seconds

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

like image 340
EmaadP Avatar asked Apr 01 '13 16:04

EmaadP


People also ask

How do you stop someone from execution at a certain time?

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.

How do you call a function repeatedly after a fixed time interval in Java?

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.

How do I make my computer wait in Java?

Thread. sleep(1000); This will sleep for one second until further execution. The time is in milliseconds or nanoseconds.


2 Answers

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

like image 165
nate_weldon Avatar answered Oct 31 '22 13:10

nate_weldon


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);
like image 38
Juvanis Avatar answered Oct 31 '22 12:10

Juvanis