Java定时任务问题。有没有一种方法能使定时任务不受程序重启的影响?

比如第一次启动程序开启一个定时任务,每一小时执行一次某任务,但是刚好在这期间(一小时内)程序重启了,希望在程序重启后,定时任务继续上一次的状态,而不是重新计时。不知道有什么方法可以解决这个问题?

第1个回答  2012-09-24
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class ClockTest {
public static void main(String[] args) throws Exception {
new ClockTest().start();
}

private long timestamp;
private File file = new File("clocktest.properties");
private Properties props = new Properties();

public void start() throws Exception {
loadTime();
while (true) {
waiting();
doJob();
setTime();
saveTime();
}
}

private void waiting() throws InterruptedException {
while (true) {
long now = System.currentTimeMillis();
if (now > timestamp) {
break;
}
long over = (timestamp - now) / 1000;
System.out.println((over / 60) + " 分 " + (over % 60) + " 秒后执行任务");
Thread.sleep(1000);
}
}

private void doJob() {
// 需要执行的任务
System.out.println("do job!");
}

private void setTime() {
timestamp = System.currentTimeMillis() + 3600 * 1000;
}

private void saveTime() throws FileNotFoundException, IOException {
FileOutputStream output = new FileOutputStream(file);
props.setProperty("timestamp", String.valueOf(timestamp));
props.store(output, "this is timestamp savefile");
output.flush();
output.close();
}

private void loadTime() throws IOException, FileNotFoundException {
if (file.exists()) {
props.load(new FileInputStream(file));
timestamp = Long.parseLong(props.getProperty("timestamp", "0"));
}
}
}
第2个回答  2012-09-24
没实现过类似的功能。但可以有一个思路,系统的时钟无论是关机还是重启都会一直执行,不会重新清零,如果你的程序计时能和系统时钟进行绑定.......本回答被提问者和网友采纳
第3个回答  2012-09-24
pgkz