使用ScheduledThreadPoolExecutor
实现定时任务 ,如下样例,定时输出系统时间,每隔两秒执行一次。 Thread.sleep作用是线程执行的时间,假如处理业务时间是10秒
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(DateFormatUtils.format(System.currentTimeMillis(), "HH:mm:ss SSS"));
}
}, 0, 2, TimeUnit.SECONDS);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
}
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
executor .scheduleAtFixedRate(new Runnable() {
int i = 0;
@Override
public void run() {
System.out.println("执行"+i++);
if(i==10){
executor .shutdown();
}
}
},0,1000, TimeUnit.MILLISECONDS);
}