1
我有一個應該基於Timer.schedule運行的TiimerTask。 問題是它唯一的應用程序啓動時運行一次...... 也許這件事情懸而未決,但我不明白什麼...Java Timer.schedule只運行一次
這是我的類擴展TimerTask的
public class ClientScheduler extends TimerTask {
public String serverUrl = Start.getHost();
public String append = "/client/checkVersion";
public String numeroClient = null;
public String actualVersion = null;
public String filePrefix = "eparkclient-";
public String fileSuffix = "-jar-with-dependencies.jar";
private final Logger logger = Logger.getLogger(ClientScheduler.class);
public ClientScheduler() {
}
@Override
public void run() {
logger.debug("Scheduler starts");
String finalUrl = null;
try {
numeroClient = PropertyConfig.getClientId();
actualVersion = PropertyConfig.getFirmwareVersion();
finalUrl = serverUrl + append + "?numeroClient=" + numeroClient;
HttpConnection http = new HttpConnection();
String result = http.getHTTPResponse(finalUrl);
JSONObject json = new JSONObject(result);
String firmwareVersion = json.getString("firmwareVersion");
Boolean updated = json.getBoolean("firmwareUpdated");
if(!actualVersion.equalsIgnoreCase(firmwareVersion)){
//scarico il file dall'ftp
FTPDownload ftp = new FTPDownload();
String filename = filePrefix+firmwareVersion+fileSuffix;
logger.debug("filename è "+filename);
boolean success = ftp.getFile(filename);
if(success) {
//scrivo la versione nuova sul file
PropertyConfig.setFirmwareVersion(firmwareVersion);
//comunico al server l'aggiornamento riuscito
HttpConnection answer = new HttpConnection();
String url = serverUrl + "/client/pushUpdate?numeroClient=" + numeroClient + "&firmwareVersion=" +
firmwareVersion + "&updated=0";
String r = answer.getHTTPResponse(url);
System.exit(0);
}
} else if(actualVersion.equalsIgnoreCase(firmwareVersion) && !updated){ //ho riavviato, devo aggiornare il DB
HttpConnection answer = new HttpConnection();
String url = serverUrl + "/client/pushUpdate?numeroClient=" + numeroClient + "&firmwareVersion=" +
firmwareVersion + "&updated="+!updated;
String r = answer.getHTTPResponse(url);
} else {
logger.debug("Non dobbiamo fare niente");
}
} catch (IOException e) {
logger.error("Errore Property", e);
}
}
}
任務被稱爲當應用程序以這種方式啓動時
public static void main(String[] args) throws Exception {
logger.info("L'ip del client è " + getCurrentIP());
//faccio partire lo scheduler
logger.debug("Scheduler called");
Timer timer = new Timer();
timer.schedule(new ClientScheduler(), 10*1000);
你閱讀[文件](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html#schedule- java.util.TimerTask中,長期)?你需要調用一個三參數'schedule'方法來重複執行。 – VGR