需要管理員權(quán)限
package com.siqi;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.TimerTask;
public class OSTime extends TimerTask{
public void run(){
try{
URLConnection conn = new URL("http://www.baidu.com")
.openConnection();
String dateStr = conn.getHeaderField("Date");
System.out.println("獲取到的服務(wù)器時(shí)間:" + dateStr);
DateFormat httpDateFormat = new SimpleDateFormat(
"E, dd MMM yyyy HH:mm:ss z", Locale.US);
httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Date date = httpDateFormat.parse(dateStr);
String currDate = new SimpleDateFormat("yyy-MM-dd").format(date);
String currTime = new SimpleDateFormat("HH:mm:ss").format(date);
setTime(currDate, currTime);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setTime(String date, String time){
String osName = System.getProperty("os.name");
String cmd = "";
try{
Process execTime;
Process execDate;
Process execTime;
if (osName.matches("^(?i)Windows.*$")){ //windows系統(tǒng)
cmd = " cmd /c date " + date;
Process execDate = Runtime.getRuntime().exec(cmd);
cmd = " cmd /c time " + time;
execTime = Runtime.getRuntime().exec(cmd);
}
else { //linux系統(tǒng)
cmd = " date -s " + date;
execDate = Runtime.getRuntime().exec(cmd);
cmd = " date -s " + time;
execTime = Runtime.getRuntime().exec(cmd);
}
if (execDate.waitFor() == 0)
System.out.println("設(shè)置系統(tǒng)日期成功:" + date);
else
System.out.println("設(shè)置系統(tǒng)日期成功:" + date);
if (execTime.waitFor() == 0)
System.out.println("設(shè)置系統(tǒng)時(shí)間成功:" + time);
else
System.out.println("設(shè)置系統(tǒng)時(shí)間失?。? + time);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.siqi;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Properties;
import java.util.Timer;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Start{
public static void main(String[] args){
try{
InputStream in = new FileInputStream(new File("config.properties"));
Properties property = new Properties();
property.load(in);
String cycle = property.getProperty("cycle");
System.out.println(cycle);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
String result = engine.eval(cycle).toString();
double cycleDouble = Double.parseDouble(result);
int cycleInt = (int)cycleDouble;
System.out.println("定時(shí)器執(zhí)行周期為(單位ms) " + cycleInt);
OSTime ostime = new OSTime();
Timer timer = new Timer();
timer.schedule(ostime, 1000L, cycleInt);
}
catch (Exception e) {
e.printStackTrace();
}
}
}