How to make Java program exit after a couple of seconds

北城以北 提交于 2019-11-29 08:11:00

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

From System.exit(int) method documentation:

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

If you need to execute something during the time waiting for exit, you could create a control thread, that will just wait for the right time to perform the exit like this:

public class ExitFewMiliseconds {

    public static void main(String args[]) {

        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.exit(0);
            }
        }).start();

        while (true) {
            System.out.println("I'm doing something");
        }
    }

}

If nothing shall be executing while waiting for exit, you could simply use a Thread.sleep(ms)

The 0 you pass into System.exit(0) has nothing to do with how long it will wait before exiting. Javadocs are your friend. From the javadoc:

The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

Other answers already cover how to wait 5 seconds before exiting if you really need to do that.

tarunajain
import java.util.Timer;
import java.util.TimerTask;

/**
 * Simple demo that uses java.util.Timer to schedule a task 
 * to execute once 5 seconds have passed.
 */
class Reminder {

    Timer timer;

    public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds * 1000);
    }

    class RemindTask extends TimerTask {
        public void run() {
            System.out.format("Time's up!%n");
            System.exit();
            timer.cancel(); //Terminate the timer thread
        }
    }

    public static void main(String args[]) {
        new Reminder(10);
        System.out.format("Task scheduled.%n");
    }
}

In this way you can use the Timer class and exit the system after a particular time interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!