20 计划任务
20.1 使用案例
public class ThreadPool {
private static final ScheduledExecutorService executor = new
ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory());
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args){
// 新建一个固定延迟时间的计划任务
executor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
if (haveMsgAtCurrentTime()) {
System.out.println(df.format(new Date()));
System.out.println("大家注意了,我要发消息了");
}
}
}, 1, 1, TimeUnit.SECONDS);
}
public static boolean haveMsgAtCurrentTime(){
//查询数据库,有没有当前时间需要发送的消息
//这里省略实现,直接返回true
return true;
}
}20.2 类结构
20.3 主要方法介绍
20.3.1 schedule

Delayed接口
ScheduledFuture接口
RunnableScheduledFuture接口
ScheduledFutureTask类
20.3.2 scheduledAtFixedRate
20.3.3 scheduledAtFixedDelay
20.3.4 delayedExecute
20.4 DelayedWorkQueue
20.4.1 take
20.4.2 offer
20.5 总结
Last updated
Was this helpful?