/**
* @(#)DelayTaskEngine.java 2011-7-25 Copyright 2011 it.kedacom.com, Inc. All
* rights reserved.
*/
//package org.comet4j.core.util;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* ???????????????????????????????????????????????????taskId?????
* @author xiaojinghai
* @date 2011-7-25
*/
public class DelayTask {
private final int cpuCoreNumber = Runtime.getRuntime().availableProcessors();
private final ScheduledExecutorService scheduler;
private final Map> taskHandles = new ConcurrentHashMap>();
public DelayTask() {
scheduler = Executors.newScheduledThreadPool(cpuCoreNumber);
}
public DelayTask(int cpuCoreNumber) {
scheduler = Executors.newScheduledThreadPool(cpuCoreNumber);
}
/**
* ????????????????????????????????????????????????????
* @param taskId ??Id,?????????????
* @param task ???????
* @param delay ????
* @param unit ???????
*/
@SuppressWarnings("unchecked")
public void delay(String taskId, Runnable task, long delay, TimeUnit unit) {
ScheduledFuture taskHandle = taskHandles.get(taskId);
if (taskHandle == null || taskHandle.isDone()) {
taskHandle = (ScheduledFuture) scheduler.schedule(task, delay, unit);
} else {
taskHandle.cancel(true);
taskHandle = (ScheduledFuture) scheduler.schedule(task, delay, unit);
}
taskHandles.put(taskId, taskHandle);
}
/**
* ???????????
* @param taskId ??Id
*/
public void cancel(String taskId) {
ScheduledFuture taskHandle = taskHandles.get(taskId);
if (taskHandle != null && !taskHandle.isDone()) {
taskHandle.cancel(true);
}
}
/**
* ???????????
*/
public void cancelAllTask() {
for (String taskId : taskHandles.keySet()) {
ScheduledFuture taskHandle = taskHandles.get(taskId);
if (taskHandle != null && !taskHandle.isDone()) {
taskHandle.cancel(true);
}
}
}
/**
* ????????????????????????
*/
public void shutdown() {
scheduler.shutdown();
}
}