Java to achieve the computer regularly shutdown method

  • 2020-04-01 03:34:11
  • OfStack

This article illustrates how to register Java as a Windows service program and a simple Java timing shutdown program code, to share for your reference. Specific methods are as follows:

I. problems:

Recently, I want to find a software to control the shutdown time of the computer. I found several software on the Internet, all of which are visual interface software that can set the specific shutdown time. Because I want to write the shutdown program is running on someone else's machine, can only let the machine in the evening from 17:00 to 23:00 25 before the Internet, to 23:00 25 can automatically shut down. In order to let others not feel the "existence" of this software (lest the user turn off the regular shutdown software), so I want to register the shutdown software as a service, run in the background. Here's how to register a Java program as a Windows service using javaService.

Ii. Implementation method

1. Use javaService to register Java programs for Windows service

1) download javaService
Visit http://javaservice.objectweb.org/ to download the Windows version of javaService files, I download javaService - 2.0.10. Rar, the latest version of the game is "2.0.10.

(2) install javaService
Unzip our download of javaServices to a directory, I am unzip to directory "D:/software/ javaservice-2.0.10" (unzip to any directory can, had better not unzip to the Chinese directory, province of the problem)

Write the regular shutdown code
1)     The name of the class is:
Com. Test. The timer. TimerShutDownWindows
2)     After writing Java files into the form of a class, the derived classes in the directory "D: / software/JavaService - 2.0.10 / classes/com/test/timer". That is to put the exported com package
"D:/software/ javaservice-2.0.10 /classes" directory.

Register the Java program as a Windows service
Enter the directory "D:/software/ javaservice-2.0.10" and execute the following command:

JavaService.exe -install MyShutDownService "%JAVA_HOME%"/jre/bin/server/jvm.dll -Djava.class.path="%JAVA_HOME%"/lib/tools.jar;D:/software/JavaService-2.0.10/classes -start com.test.timer.TimerShutDownWindows

Where the parameter after "-install" is the name of the service, the parameter after "-start" is the name of the class to be started, and the parameter after "djava.class.path" is
"D:/software/ javaservice-2.0.10 /classe" address is the path where my "TimerShutDownWindows" class is stored. In practice, I can change it to my own classPath.

Here are a few things to note:

1)     "%JAVA_HOME%" JDK directory, if no JDK directory is configured, replaced with the actual absolute address of the JDK.

2)     -djava.class.path is required because the CLASSPATH variable of the system cannot be accessed when the service starts, so it must be declared here. If you have a large number of jars, to avoid writing commands that are too long, you can use the "-djava.ext. Dirs = directory where you are jars" parameter.

3)     After the service is added, you can type in the "services.msc" command from the command line to view all the services, and you can modify the startup type of the service (auto startup or manual startup, etc.).

(5) test

1)   Start the service

When we are finished registering the service, we can start the service by commanding "net start MyShutDownService". After the service starts, the my_shutdown.log log file will be generated in the ddisk root directory.

2)   Close the service

If we want to close the service, we can do so by using the command "net stop MyShutDownService".

3)   Remove the service

When we want to delete the service, we can use the command "sc delete MyShutDownService" to delete the service.

2. Regularly shutdown code

package com.test.timer;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimerShutDownWindows {
   
    private static long m_nDetectInterval = 5000;
   
    private static long m_lLastMilliSeconds = 0;
   
    private static int m_nUsePCMinHour = 17;
   
    private static int m_nUseComputerMaxHour = 23;
   
    private static int m_nMinutes = 25;
   
    private static String m_sLogFile = "D:" + File.separator
           + "my_shutdown.log";
   
    private static boolean bHasShutDownPC = false;
    /**
      * @param args
      */
    public static void main(String[] args) {
       //1. Start a separate thread to detect
       Thread aThread = new Thread(new TimerDetector());
       aThread.start();
    }
    /**
      * Defining inner classes
      *
      * @author Administrator
      *
      */
    static class TimerDetector implements Runnable {
       /*
         * (non-Javadoc)
         *
         * @see java.lang.Runnable#run()
         */
       public void run() {
           //1. Get the log file
           PrintWriter out = null;
           SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           try {
              out = new PrintWriter(new FileWriter(m_sLogFile, true), true);
           } catch (IOException e1) {
              out = null;
              e1.printStackTrace();
           }
           //2. Record service startup time
           appendLog(out, " Service startup time: " + df.format(new Date()));
           while (true) {
              //1. Determine whether the current system time has been modified
              boolean bShoudShutDownPC = validateShoudShutDownPC(out);
              if (bShoudShutDownPC) {
                  //Validation failed, force shutdown
                  exectueShutDown(out);
              } else {
                  bHasShutDownPC = false;
              }
              //2.
when the current thread is asleep               try {
                  Thread.sleep(m_nDetectInterval);
              } catch (InterruptedException e) {
                  appendLog(out, e.getMessage());
              }
           }
       }
       /**
         * Verify that the current time is the time for shutdown
         *
         * @return
         */
       private boolean validateShoudShutDownPC(PrintWriter _out) {
           //1. Determine whether the system time
has been modified            boolean bHasModifySystemTime = detectModifySytemTime(_out);
           appendLog(_out, "bHasModifySystemTime : " + bHasModifySystemTime);
           if (bHasModifySystemTime) {
              return bHasModifySystemTime;
           }
           //2. If the system time is not modified, determine whether the current time has exceeded the specified time
           boolean bShoudSleep = nowIsSleepTime();
           appendLog(_out, "bShoudSleep : " + bShoudSleep);
           if (bShoudSleep) {
              return bShoudSleep;
           }
           return false;
       }
       /**
         * Determine whether or not the current time should take a break
         *
         * @return
         */
       private boolean nowIsSleepTime() {
           //1. Gets the current hours and minutes
           Calendar aCalendar = Calendar.getInstance();
           int nHour = aCalendar.get(Calendar.HOUR_OF_DAY);
           int nMinute = aCalendar.get(Calendar.MINUTE);
           //2. Determine whether the current hour is within the PC usable time, and the maximum hour is 23
           if (nHour < m_nUsePCMinHour) {
              return true;
           }
           //


           if ((nHour >= m_nUseComputerMaxHour) && (nMinute >= m_nMinutes)) {
              return true;
           }
           //3. Non-break time
           return false;
       }
       /**
         * Determine if someone changed the system time, and return if someone changed the system time true . <BR>
         * Otherwise returns false
         *
         * @return
         */
       private boolean detectModifySytemTime(PrintWriter _out) {
           //1. Time of the first detection system
           if (m_lLastMilliSeconds == 0) {
              m_lLastMilliSeconds = System.currentTimeMillis();
              return false;
           }
           //2. Detect the difference between two times
           long lInteral = System.currentTimeMillis() - m_lLastMilliSeconds;
           lInteral = Math.abs(lInteral);
           //3. Judge the time interval of two times. The two results may not be exactly equal to m_nDetectInterval, and the error is allowed to be 1 minute
           long lMaxInterval = m_nDetectInterval + 60 * 1000;
           appendLog(_out, "lInteral : ::" + lInteral);
           appendLog(_out, "lMaxInterval : ::" + lMaxInterval);
           if (lInteral > lMaxInterval) {
              //Someone changed the system time to force the shutdown
              return true;
           }
           //4. The last detection time
was recorded only if no one modified the time            m_lLastMilliSeconds = System.currentTimeMillis();
           return false;
       }
       /**
         * Writes log information to the specified stream
         *
         * @param _outWriter
         * @param _sAppendContent
         */
       private void appendLog(PrintWriter _outWriter, String _sAppendContent) {
           if (_outWriter == null) {
              return;
           }
           _outWriter.println(_sAppendContent);
       }
       /**
         * Execute shutdown command
         */
       private void exectueShutDown(PrintWriter _out) {
           if (bHasShutDownPC) {
              SimpleDateFormat df = new SimpleDateFormat(
                     "yyyy-MM-dd HH:mm:ss");
              appendLog(_out, " The system is about to shut down. , Current time: " + df.format(new Date()));
              return;
           }
           appendLog(_out, " Someone modified the system time, the system forced shutdown! ");
           //Shutdown < br / >            try {
              Runtime.getRuntime().exec(
                     "shutdown -s -t 120 -c /" It's late. It's time to go to bed ,2 Shut down the computer in minutes. /"");
           } catch (IOException e) {
              appendLog(_out, e.getMessage());
           }
           bHasShutDownPC = true;
       }
    }
}

I hope this article has been helpful to your Java programming.


Related articles: