定时器的应用
参考:http://www.fx114.NET/qa-126-102338.aspx
主要是了解定时器使用的技巧,使其间隔相同时间或不同时间一直执行下去,或者某个固定的时刻或日期,执行,有相关的插件可以实现。主要是当遇到问题的时候,想到有这样的解决方案
Timer类:一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。
特有方法:
schedule(TimerTask task,long delay); 安排在制定延迟后执行指定的任务。
schedule(TimerTask task,long delay,long period);安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
TimerTask类:由 Timer 安排为一次执行或重复执行的任务。
boolean cancel(); 取消此计时器任务
abstract void run(); 此计时器任务要执行的操作。
示例代码:
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalTimerTest {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("bombing");
}
},10000);
new Timer().schedule(
new TimerTask(){
public void run(){
System.out.println("bombing");
}
},
10000,
3000);
/*
//相隔相同的时间,运行定时器
public static void main(String[] args) {
class MyTimerTask extends TimerTask{
public void run(){
System.out.println("bombing");
new Timer().schedule(new MyTimerTask(), 2000);
}
}
new Timer().schedule(new MyTimerTask(), 2000);
}
*/
/*
//可以根据生成不同间隔的算法,使定时器一直按照不同的时间间隔执行下去
static int count=0;
public static void main(String[] args) {
class MyTimerTask extends TimerTask{
public void run(){
count = (count+1)%2;
System.out.println("bombing");
new Timer().schedule(new MyTimerTask(),2000+2000*count);
}
new Timer().schedule(new MyTimerTask(), 2000);
}
*/
/*
//两秒之后,三秒之后再炸
new Timer().schedule(new TimerTask(){
public void run(){
System.out.println("bombing");
new Timer().schedule(new TimerTask(){
public void run(){
System.out.println("bombing");
}
},
3000);
}
},
2000);
*/
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}