The examples in this article describe how to register Java as a Windows service program and a simple Java scheduled shutdown program code, and share it with you for your reference. The specific method is as follows:
1. Question:
I recently wanted to find a software to control the computer's shutdown time, and I found a few on the Internet. They were all software with visual interfaces that could set specific shutdown times. Since the shutdown program I want to write runs on someone else's machine, the machine can only access the Internet from 17:00 to 23:25 in the evening, and it can automatically shut down at 23:25. In order to prevent others from feeling the "existence" of this software (to prevent users from closing the scheduled shutdown software themselves), I want to register the shutdown software as a service and run it in the background. Here is an introduction to how to use the javaService software to register a java program as a windows service.
2. Implementation method:
1. Use javaService to register the java program as a windows service
① Download javaService
Visit the URL http://javaservice.objectweb.org/ to download the windows version of javaService file. I downloaded JavaService-2.0.10.rar. The latest version is "2.0.10".
② Install javaService
Unzip the javaServices we downloaded to a directory. I unzipped it to the directory "D:/software/JavaService-2.0.10" (you can unzip it to any directory. It is best not to unzip it to a Chinese directory to avoid problems)
③ Write scheduled shutdown code
1) The name of the class is:
com.test.timer.TimerShutDownWindows
2) Export the written java file as a class, and put the exported class in the directory "D:/software/JavaService-2.0.10/classes/com/test/timer". That is, put the exported com package in the "D:/software/JavaService-2.0.10/classes" directory.
④ To register the java program as a windows service, enter the "D:/software/JavaService-2.0.10" directory and execute the following command:
Copy the 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, 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" "The address is the path where my "TimerShutDownWindows" class is stored. In actual applications, just change it to your own classPath.
There are a few points to note here:
1) "%JAVA_HOME%" jdk directory, if the jdk directory is not configured, replace it with the actual absolute address of the jdk.
2) -Djava.class.path is necessary because the system's CLASSPATH variable cannot be accessed when the service is started, so it must be declared here; if there are many jars, to avoid writing too long commands, we can use "-Djava. ext.dirs=the directory where jars is located" parameter.
3) After the service is added, you can type the "services.msc" command on the command line to view all services, and modify the startup type of the service (automatic startup or manual startup, etc.).
⑤ Test
1) Start the service
After we register the service, we can start the service through the command "net start MyShutDownService". After the service is started, the my_shutdown.log log file will be generated in the root directory of the D drive.
2) Close the service
If we want to shut down the service, we can shut down the service by command "net stop MyShutDownService".
3) Delete service
When we want to delete the service, we can use the command "sc delete MyShutDownService" to delete the service.
2. Scheduled shutdown code
Copy the 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 {
/* Time interval to detect whether shutdown is required*/
private static long m_nDetectInterval = 5000;
/* Record the time of the last detection, in milliseconds */
private static long m_lLastMilliSeconds = 0;
/* Minimum hours that the computer can be used */
private static int m_nUsePCMinHour = 17;
/* The maximum number of hours the computer can be used */
private static int m_nUseComputerMaxHour = 23;
/* If the minutes exceed this time, shut down the computer */
private static int m_nMinutes = 25;
/* The 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 shutdown program*/
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();
}
/**
* Define inner class
*
* @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) {
// Verification failed, forced shutdown
executeShutDown(out);
} else {
bHasShutDownPC = false;
}
// 2. The current thread sleeps
try {
Thread.sleep(m_nDetectInterval);
} catch (InterruptedException e) {
appendLog(out, e.getMessage());
}
}
}
/**
* Verify whether the current time is the time that needs to be shut down
*
* @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 has not been modified, determine whether 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 be a 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;
}
// 23 o'clock needs to be judged individually, and you should take a break after 23:30
if ((nHour >= m_nUseComputerMaxHour) && (nMinute >= m_nMinutes)) {
return true;
}
// 3. Non-rest time
return false;
}
/**
* Determine whether someone has modified the system time. If someone has modified the system time, return true, <BR>
* Otherwise return false
*
* @return
*/
private boolean detectModifySytemTime(PrintWriter _out) {
// 1. Detect system time for the first time
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. Determine the time interval between two times. The two results may not be exactly equal to m_nDetectInterval. The allowed 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 if no one modifies the 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 shutdown command
*/
private void executeShutDown(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 and the system was forced to shut down!");
// Shut down
try {
Runtime.getRuntime().exec(
"shutdown -s -t 120 -c /" It's very late, it's time to go to bed, shut down the computer after 2 minutes. /"");
} catch (IOException e) {
appendLog(_out, e.getMessage());
}
bHasShutDownPC = true;
}
}
}
I hope this article will be helpful to everyone’s Java programming.