How to make Java program exit after a couple of seconds

EmaadP picture EmaadP · Apr 1, 2013 · Viewed 18.1k times · Source

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

Answer

nate_weldon picture nate_weldon · Apr 1, 2013

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