Java code for computer Timed Shutdown

Source: Internet
Author: User
Tags difference between two times export class

This article introduces how to register java as a windows service program and then describes a simple java Timed Shutdown program code. If you need it, refer to this article.

Recently, I want to find a software to control the shutdown time of my computer. I have found several software on the Internet that can be used to set the specific shutdown time on the visual interface. Since the Shutdown program I want to write is running on another machine, the machine can only access the Internet at pm to PM, and can be automatically shut down at pm. In order to make others feel that the software "exists" (so that users do not close the Timed Shutdown software themselves), I want to register the shutdown software as a service and run it in the background. This section describes how to use the assumervice software to register a java program as a windows service.
I. Use assumervice to register a java program to serve windows
[1] downloading assumervice
Visit the web site http://javaservice.objectweb.org/download the windows version of the movie ervice file, I download is movie ervice-2.0.10.rar, the latest version is "2.0.10 ".
[2] installing assumervice
Decompress the downloaded javaServices to a directory, I decompress it to the directory "D:/software/JavaService-2.0.10" (decompress it to any directory can be, it is best not to decompress it to the Chinese directory, saving problems)
[3] compile the Timed Shutdown code. For details, refer to the Timed Shutdown code in Chapter 2.
1) for specific code, see Chapter 2. The class name is:
Com. test. timer. TimerShutDownWindows
2) write the java file to export the form of class, the export class to the directory "D:/software/JavaService-2.0.10/classes/com/test/timer. That is, place the exported com package
Under the D:/software/JavaService-2.0.10/classes directory.
[4] registering a java program as a windows Service
Go to the D:/software/JavaService-2.0.10 directory and execute the following command:
Assumervice.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
The parameter after "-install" is the service name, and the "-start" parameter is the class name to be started.
"D:/software/JavaService-2.0.10/classe" address is my "TimerShutDownWindows" class storage path, the actual application is changed to your own classPath.
Note the following points:
1) "% JAVA_HOME %" jdk directory. If the jdk directory is not configured, replace it with the actual absolute address of jdk.
2)-Djava. class. path is required because the system's CLASSPATH variable cannot be accessed when the service is started, so it must be declared here. If there are many jar files, to avoid writing too long commands, we can use "-Djava. ext. dirs = jars Directory "parameter.
3) after adding a service, you can enter "services. msc command to view all services, and can modify the Service Startup Type (automatic start or manual start.
[5] Test
1) start the service
After registering the service, run the "net start MyShutDownService" command to start the service. After the service is started, the my_shutdown.log file is generated in the D root directory.
2) Close the service
To disable the service, run the "net stop MyShutDownService" command.
3) delete a service
To delete a service, run the "SC delete MyShutDownService" command to delete the service.
Ii. Timed Shutdown code

The Code is as follows: Copy 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 {
/* Interval for checking whether shutdown is required */
Private static long m_nDetectInterval = 5000;
/* Record the last detection time, in milliseconds */
Private static long m_lLastMilliSeconds = 0;
/* Minimum hours for computers */
Private static int m_nUsePCMinHour = 17;
/* Maximum hours for computers */
Private static int m_nUseComputerMaxHour = 23;
/* If the time exceeds this time, shut down the computer */
Private static int m_nMinutes = 25;
/* Storage location of the log file */
Private static String m_sLogFile = "D:" + File. separator
+ "My_shutdown.log ";
/* Record whether the current system has started the automatic program close */
Private static boolean bHasShutDownPC = false;
/**
* @ Param args
*/
Public static void main (String [] args ){
// 1. Enable a separate thread for Detection
Thread aThread = new Thread (new TimerDetector ());
AThread. start ();
}
/**
* Define internal 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 the service start time
AppendLog (out, "service start time:" + df. format (new Date ()));
While (true ){
// 1. Determine whether the current system time has been modified
Boolean bShoudShutDownPC = validateShoudShutDownPC (out );
If (bShoudShutDownPC ){
// Force Shutdown if verification fails
Exectueshudown (out );
} Else {
BHasShutDownPC = false;
}
// 2. The current thread is sleeping
Try {
Thread. sleep (m_nDetectInterval );
} Catch (InterruptedException e ){
AppendLog (out, e. getMessage ());
}
}
}
/**
* Verify whether 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, check whether the current time has exceeded the specified time.
Boolean bShoudSleep = nowIsSleepTime ();
AppendLog (_ out, "bShoudSleep:" + bShoudSleep );
If (bShoudSleep ){
Return bShoudSleep;
}
Return false;
}
/**
* Determine whether the current time should be the rest time
*
* @ Return
*/
Private boolean nowIsSleepTime (){
// 1. Get the current hour and minute
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 time when the PC can be used. The maximum hour is 23.
If (nHour <m_nUsePCMinHour ){
Return true;
}
// You need to make a separate judgment at. You should take a rest after.
If (nHour> = m_nUseComputerMaxHour) & (nMinute> = m_nMinutes )){
Return true;
}
// 3. Non-Rest Time
Return false;
}
/**
* Determines if someone has modified the system time. If someone has modified the system time, true is returned. <BR>
* Otherwise, false is returned.
*
* @ Return
*/
Private boolean detectModifySytemTime (PrintWriter _ out ){
// 1. First detection system time
If (m_lLastMilliSeconds = 0 ){
M_lLastMilliSeconds = System. currentTimeMillis ();
Return false;
}
// 2. Difference between two times of Detection
Long lInteral = System. currentTimeMillis ()-m_lLastMilliSeconds;
LInteral = Math. abs (lInteral );
// 3. Determine the interval of two times. The two results are not necessarily equal to m_nDetectInterval, and the error is 1 minute.
Long lMaxInterval = m_nDetectInterval + 60*1000;
AppendLog (_ out, "lInteral:" + lInteral );
AppendLog (_ out, "lMaxInterval:" + lMaxInterval );
If (lInteral> lMaxInterval ){
// Someone modified the system time and forced shutdown
Return true;
}
// 4. The last detection time is recorded only when no one modifies the time.
M_lLastMilliSeconds = System. currentTimeMillis ();
Return false;
}
/**
* Write log information to the specified stream
*
* @ Param _ outWriter
* @ Param _ sAppendContent
*/
Private void appendLog (PrintWriter _ outWriter, String _ sAppendContent ){
If (_ outWriter = null ){
Return;
}
_ OutWriter. println (_ sAppendContent );
}
/**
* Run the shutdown command.
*/
Private void exectueshudown (PrintWriter _ out ){
If (bHasShutDownPC ){
SimpleDateFormat df = new SimpleDateFormat (
"Yyyy-MM-dd HH: mm: ss ");
AppendLog (_ out, "the system is about to close. Current Time:" + df. format (new Date ()));
Return;
}
AppendLog (_ out, "Someone modified the system time and the system forced shutdown! ");
// Shutdown
Try {
Runtime.getruntime(cmd.exe c (
"Shutdown-s-t 120-c/" is very late. It is time to go to bed and shut down the computer two minutes later. /"");
} Catch (IOException e ){
AppendLog (_ out, e. getMessage ());
}
BHasShutDownPC = true;
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.