Java定时任务de实现一般有三种方法:thread实现、TimerTask实现、ScheduledExecutorService实现三种。 1 thread实现(不建议) // thread 实现 public static void threadTask(){ // run in a second final long timeI
Java定时任务de实现一般有三种方法:thread实现、TimerTask实现、ScheduledExecutorService实现三种。
1 thread实现(不建议)
// thread 实现public static void threadTask(){
// run in a second
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
// run task
System.out.println("Run Task ...... ");
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new
2 TimerTask实现
可以控制任务启动和取消,可以设置第一次任务运行的delay时间。
TimerTask task = new TimerTask(){
public void run() {
// run task
System.out.println("Run Task ...... ");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000;
//timer.scheduleAtFixedRate(task, delay,intevalPeriod);
timer.scheduleAtFixedRate(task, new
3 ScheduledExecutorService实现
通过线程池的方式来执行任务,可以设定第一次运行任务delay时间,较好的时间间隔约定。
Runnable runnable = new Runnable() {
public void run() {
// run task
System.out.println("Run Task ...... ");
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
service.scheduleWithFixedDelay(runnable, 0, 1, TimeUnit.SECONDS);
}