一个简单的Timer例子
山哥 http://csdn.blog.net/duoshan
有时想要换一定的间隔时间执行重复的任务,java.util.Timer可以很简单的帮你实现。当然你也可以用多线程来实现。下面是用java.util.Timer来实现这个功能。
//myTask.java 定义TimerTask任务,我们会在doTask中调用.
//这里只是简单的打印一下任务参数
public class myTask
extends java.util.TimerTask {
String jobName;
private int i;
public void run() { //run in interface Runnabl
System.out.println(jobName);
}
public myTask(String jobName) {
this.jobName = jobName;
}
}
//doTask.java
import java.util.*;
import java.io.*;
public class doTask {
private java.util.Timer timer;
private java.util.TimerTask task;
public doTask(java.util.TimerTask task) {
this.timer = new Timer();
this.task = task;
}
public void start(int delay, int internal) {
timer.schedule(task, delay * 1000, internal * 1000);//利用timer.schedule方法
}
public static void main(String[] args) {
java.util.TimerTask task1 = new myTask(" Job 1");
java.util.TimerTask task2= new myTask("Job 2");
doTask pt = new doTask(task1);
pt.start(1,3);
doTask pt2 = new doTask(task2);
pt2.start(1,1);
}
}
结果如下;
Job 1
Job 2
Job 2
Job 2
Job 1
Job 2
Job 2
Job 2
.
.