一、使用原始线程实现定时任务:(每1秒执行一次任务,共执行5次)
public class Task1{
public static void main(String[] args){
final int interval = 1000;
Runnable runnable = new Runnable(){
public void run(){
int count = 0;
while(count<5){
System.out.println("任务执行...");
count++;
try{
Thread.sleep(interval);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
二、使用Timer和TimerTask实现定时任务:(每1秒检查一次时间,每到20秒时执行任务)
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class Task2{
public static void main(String args[]){
final int interval = 1000;
final int secondParam = 20;
Timer t = new Timer();
TimerTask task = new TimerTask(){
public void run(){
Calendar calendar = Calendar.getInstance();
int second =calendar.get(Calendar.SECOND);
if(second==secondParam){
System.out.println("任务执行...");
}else{
System.out.println("任务不执行...");
}
}
};
t.schedule(task,0,interval);
}
}
三、使用ScheduledExecutorService实现定时任务:(每1秒执行一次任务,共执行5次后程序结束)
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Task3{
public static void main(String[] args){
final int interval = 1;
final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = new Runnable(){
int count = 0;
public void run(){
if(count<5){
System.out.println("任务执行...");
count++;
}else{
service.shutdown();
}
}
};
service.scheduleWithFixedDelay(runnable,0,interval,TimeUnit.SECONDS);
}
}