JDK自带的timer使用的时候会在主线程之外起一个单独的线程执行指定的计划任务,可以执行一次或反复执行多次。本篇文章主要从代码层面讲解如何用JDK自带的Timer实现一个简单的任务调度。直接上代码~
一、测试代码
package com.xzw.timer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
*
* @author xzw
*
*/
public class TestTimer {
public static void main(String[] args) {
final DateTimeFormatter destDtf = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
Runnable runnable = new Runnable() {
@Override
public void run() {
// task to run goes here
System.out.println("Hello!!" + destDtf.format(LocalDateTime.now()));
}
};
ScheduledExecutorService service = Executors
.newSingleThreadScheduledExecutor();
//第二个参数为首次执行的延迟时间,第三个参数为定时执行的间隔时间
service.scheduleAtFixedRate(runnable, 2, 1, TimeUnit.SECONDS);
System.out.println("I am xzw01");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("I am xzw02");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("I am xzw03");
}
}
二、测试结果
至此,一个简单的任务调度就实现了~
你们在此过程中还遇到了什么问题,欢迎留言,让我看看你们都遇到了哪些问题。