我有一个TiimerTask,它应该基于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);
答案 0 :(得分:4)
您只安排一次计时器任务。
计划方法定义为
日程安排(TimerTask任务,长延迟)
安排指定的任务 在指定的延迟后执行。
但你需要使用这种方法:
计划(TimerTask任务,长延迟,长期)
为重复固定延迟执行计划指定任务, 在指定的延迟后开始。
请在此处查看Javadoc:https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html#schedule-java.util.TimerTask-long-long-