第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"));
}
}
}