This article describes how Java is registered as a Windows service program and a simple Java timer shutdown program code, to share for everyone's reference. The specific methods are as follows:
First, the question:
Recently want to find a software to control the computer shutdown time, on the internet to find a few, are visual interface can set specific shutdown time software. Because I want to write the shutdown program is running on someone else's machine, can only let the machine in the evening 17 o'clock to 23:25 before the Internet, to the 23:25 can automatically shutdown. In order to make others feel that the software "exists" (lest the user shut down the timer itself), so I want the Gatekeeper software registered as a service in the way, running in the background. This article describes how to use the Javaservice software to register Java programs as Windows services.
Second, the realization method:
1. Use Javaservice to register Java programs for Windows services
① Download Javaservice
Visit the Web site http://javaservice.objectweb.org/Download the Windows version of the Javaservice file, I downloaded is Javaservice-2.0.10.rar, the latest version is "2.0.10."
② installation Javaservice
Decompression we downloaded the javaservices to a directory, I was extracted to the directory "d:/software/javaservice-2.0.10" (extract to any directory can be, preferably do not extract to the Chinese directory, the province of the problem)
③ Write timed shutdown code
1) The name of the class is:
Com.test.timer.TimerShutDownWindows
2 The written Java file into class form, put the derived classes under the directory "D:/software/javaservice-2.0.10/classes/com/test/timer". Which is to put the exported COM package
"D:/software/javaservice-2.0.10/classes" directory.
④ registers Java programs for Windows services
Go to the "d:/software/javaservice-2.0.10" directory and execute the following command:
Copy Code code as follows:
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
The parameter after "-install" is the name of the service, and the "-start" argument is followed by the name of the class to start, followed by the "Djava.class.path" parameter in the
"D:/software/javaservice-2.0.10/classe" Address is my "timershutdownwindows" class stored in the path, the actual application of modification for their own classpath can be.
Here are a few things to note:
1 "%java_home%" JDK directory, if no JDK directory is configured, replace with the actual absolute address of JDK.
2)-djava.class.path is necessary because the service cannot access the system's CLASSPATH variables when it is started, so it must be declared here, and if there are more jars, we can use "-djava.ext.dirs=jars" to avoid too long written commands Directory "parameter.
3 After the service is added, you can type the "services.msc" command at the command line to view all the services, and you can make modifications to the service's startup types (Autostart or manual startup, and so on).
⑤ Test
1) Start service
When we have finished registering the service, we can start the service through the command "net start Myshutdownservice", and the service will generate the My_shutdown.log log file in the D-Packing directory after startup.
2) Close the service
If we want to turn off the service, we can turn off the service by using the command "net stop Myshutdownservice".
3) Delete Service
When we want to remove the service, you can use the command "SC delete myshutdownservice" to remove the service.
2. Timed Shutdown code
Copy Code code as follows:
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 {
/* Detect if the shutdown time interval is required.
private static long m_ndetectinterval = 5000;
/* Record the last detected time in milliseconds.
private static Long m_llastmilliseconds = 0;
/* Minimum hours to use the computer/
private static int m_nusepcminhour = 17;
/* The maximum hours of use of the computer can be * *
private static int m_nusecomputermaxhour = 23;
/* If the minutes exceed this time, the shutdown computer/
private static int m_nminutes = 25;
/* The location where the log files are saved/*
private static String M_slogfile = "D:" + file.separator
+ "My_shutdown.log";
/* Log whether the current system has started the automatic shutdown program.
private static Boolean BHASSHUTDOWNPC = false;
/**
* @param args
*/
public static void Main (string[] args) {
1. Open a separate thread to detect
Thread athread = new Thread (new Timerdetector ());
Athread.start ();
}
/**
* Define inner class
*
* @author Administrator
*
*/
Static Class Timerdetector implements Runnable {
/*
* (Non-javadoc)
*
* @see Java.lang.runnable#run ()
*/
public void Run () {
1. Get 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. Log service start time
Appendlog (out, "service start time:" + Df.format (new Date ());
while (true) {
1. Determine if the current system time has been modified
Boolean BSHOUDSHUTDOWNPC = VALIDATESHOUDSHUTDOWNPC (out);
if (BSHOUDSHUTDOWNPC) {
Validation failed, forced shutdown
Exectueshutdown (out);
} else {
BHASSHUTDOWNPC = false;
}
2. The current thread sleeps under
try {
Thread.Sleep (M_ndetectinterval);
catch (Interruptedexception e) {
Appendlog (out, E.getmessage ());
}
}
}
/**
* Verify that the current time is the time required for the shutdown
*
* @return
*/
Private Boolean VALIDATESHOUDSHUTDOWNPC (PrintWriter _out) {
1. Determine if 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 if the current time exceeds the specified time
Boolean bshoudsleep = Nowissleeptime ();
Appendlog (_out, "bshoudsleep:" + bshoudsleep);
if (bshoudsleep) {
return bshoudsleep;
}
return false;
}
/**
* Determine whether the current time should rest time
*
* @return
*/
Private Boolean nowissleeptime () {
1. Get the current hour and minutes
Calendar Acalendar = Calendar.getinstance ();
int nhour = Acalendar.get (Calendar.hour_of_day);
int nminute = Acalendar.get (Calendar.minute);
2. Determine if the current hour is within the time available to use the PC, with a maximum hour of 23
if (Nhour < M_nusepcminhour) {
return true;
}
23 points need to be judged alone, more than 23 points 30 should rest
if ((Nhour >= m_nusecomputermaxhour) && (Nminute >= m_nminutes)) {
return true;
}
3. Non-rest time
return false;
}
/**
* Determine if someone has modified the system time, if someone modified the system time returns True,<br>
* Otherwise return false
*
* @return
*/
Private Boolean Detectmodifysytemtime (PrintWriter _out) {
1. First time to test system
if (M_llastmilliseconds = = 0) {
M_llastmilliseconds = System.currenttimemillis ();
return false;
}
2. Detect the difference of two times
Long linteral = System.currenttimemillis ()-m_llastmilliseconds;
Linteral = Math.Abs (linteral);
3. Judge two time interval, two times result is not necessarily equal to M_ndetectinterval, allowable error is 1 minutes
Long Lmaxinterval = m_ndetectinterval + 60 * 1000;
Appendlog (_out, "Linteral:::" + linteral);
Appendlog (_out, "Lmaxinterval:::" + lmaxinterval);
if (Linteral > Lmaxinterval) {
Someone has modified the system time, forced the shutdown
return true;
}
4. Only if no one changes the time to record the last detection time
M_llastmilliseconds = System.currenttimemillis ();
return false;
}
/**
* Write log information in the specified stream
*
* @param _outwriter
* @param _sappendcontent
*/
private void Appendlog (PrintWriter _outwriter, String _sappendcontent) {
if (_outwriter = = null) {
Return
}
_outwriter.println (_sappendcontent);
}
/**
* Execute the 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 close, current time:" + Df.format (new Date ()));
Return
}
Appendlog (_out, "someone modified the system time, the system forced shutdown!") ");
Shutdown
try {
Runtime.getruntime (). EXEC (
"Shutdown-s-t 120-c/" It's late, it's time to go to bed and turn off the computer after 2 minutes. /"");
catch (IOException e) {
Appendlog (_out, E.getmessage ());
}
BHASSHUTDOWNPC = true;
}
}
}
I hope this article will help you with your Java programming.