1. 案例一
import java.util.Timer;
import java.util.TimerTask;
/*
* author:zj
* date:2016/1/7
* function:4秒执行一次,2秒执行一次,4秒执行一次...
*/
public class MyTimerTask extends TimerTask{
static int count;
@Override
public void run() {
count=(count+1)%2;
System.out.println("执行一次.....");
Timer t=new Timer();
t.schedule(new MyTimerTask(), 2000+2000*count);
}
}
import java.util.Date;
import java.util.Timer;
public class TraditionalTimer {
//3秒后开始执行,然后每4秒执行一次,每2秒执行一次,每4秒执行一次,每2秒执行一次...
public static void main (String[] args){
Timer t=new Timer();
MyTimerTask myTimerTask=new MyTimerTask();
t.schedule(myTimerTask, 3000);
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2. 案例二
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalTimer2 {
//从2016年1月7号开始,每天凌晨零点收邮件
public static void receiveMailOnTime(){
Timer t=new Timer();
TimerTask timeTask=new TimerTask(){
public void run() {
System.out.println("receive mail here ...");
}
};
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date firstTime=new Date();
try {
firstTime = df.parse("20160107000000");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(firstTime.toString());
t.schedule(timeTask, firstTime, 24*60*60*1000);
}
public static void main (String[] args){
receiveMailOnTime();
}
}
至于其他更具体的需求,如每周一到五凌晨零点收邮件,周六日不用收邮件,这类需求可以使用Quartz开源项目来实现,具体实现方法后期将继续讨论。