Search This Blog

Showing posts with label shut down. Show all posts
Showing posts with label shut down. Show all posts

How to Schedule a Shutdown in Java - Java Code to Schedule a Shutdown

In this post, we will see how to schedule a shutdown in a computer using java program. For this, we execute the appropriate shutdown command after identifying the operating system. The following java code will schedule a shutdown after a 10 minute from execution of the code.

String os=System.getProperty("os.name").toLowerCase();
String command;
try
{
if(os.contains("windows"))
    {
    command="shutdown /s /t 600";
    }
else if(os.contains("linux")||os.contains("mac os x"))
    {
    command="shutdown -h +600";
    }
else
    throw new Exception("Unsupported OS");
Runtime.getRuntime().exec(command);
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}

How to Shutdown Computer from Java - Java Code to Shutdown Computer

Java program can cause a computer to shutdown. In order to shutdown a computer using java code, you should execute the shutdown command in that operating system. The shutdown command is different in Windows and Linux. So, we first check for the operating system. Then we execute appropriate shutdown command.


try {
            String command;
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("linux") || os.contains("mac os x"))
                command = "shutdown -h now";
            else if (os.contains("windows"))
                command = "shutdown /p";
            else
                throw new Exception("Unsupported operating system.");
            
            Runtime.getRuntime().exec(command);
            System.exit(0);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }

For Linux and Mac OS X, the command for immediate shutdown is shutdown -h now. But in Windows, it is shutdown /p. The above java code checks the operating system. Then it assumes appropriate shutdown command and then executes it. This java code can shutdown a computer.