Search code examples
javasystemexitseconds

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


Solution

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