实际执行任务的类:
package MyTask;
import java.util.TimerTask;
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("执行一次任务");
}
}
任务定时类
package MyTask;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Timer;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
public class MyTimerTask {
public static void main(String[] args) throws Exception {
//本文采用dom4J 来做xml 的解析,其中没有做 任何错误的处理判断,默认是正确的
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("src/MyTask/task.xml"));
String start = doc.getRootElement().elementText("startTime");
String intermission = doc.getRootElement().elementText("intermission");
Timer timer = new Timer();
timer.scheduleAtFixedRate( new MyTask(),
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(start),
Integer.parseInt(intermission));
}
}
xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<task>
<startTime>2011-10-18 21:40:30</startTime>
<intermission>3000</intermission>
</task>