ScheduledExecutorService改为一次性延时任务
import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; /** * 一次性延时任务 * * @author shay_deng * @since: v1.0 */ public class OneTimeScheduledExecutorService { private final static Logger logger = Logger.getLogger(OneTimeScheduledExecutorService.class); private Map<String, ScheduledExecutorService> taskMap = new HashMap<>(); /** * 添加一个任务 * * @param taskName * 任务名称 * @param command * 任务 * @param delay * 延时时间 * @param unit * 时间单位 */ public void schedule(String taskName, Runnable command, long delay, TimeUnit unit) { if (!taskMap.containsKey(taskName)) { ScheduledExecutorService task = Executors.newScheduledThreadPool(1); Runnable run = new Runnable() { public void run() { command.run();//要做的事 if (taskMap.containsKey(taskName)) {// 执行完关闭任务 taskMap.get(taskName).shutdownNow();//用完要关掉,要不然占内存 taskMap.remove(taskName); logger.info("一次性延时任务 -- >执行完成,删除任务 taskName="+taskName); } } }; task.schedule(run, delay, unit); taskMap.put(taskName, task); logger.info("一次性延时任务 -- >添加任务 taskName="+taskName); } } /** * 中途终止任务 * * @param taskName * 任务名称 */ public void shutdownNow(String taskName) { if (taskMap.containsKey(taskName)) { taskMap.get(taskName).shutdownNow(); taskMap.remove(taskName); logger.info("一次性延时任务 -- >取消任务 taskName="+taskName); } } /** * 包含此任务 * * @param taskName * @return */ public boolean containsTask(String taskName) { return taskMap.containsKey(taskName); } }
使用
/** * 检查使用状态 * * @author shay_deng * @since: v1.0 */ public class CheckUseStatus { private OneTimeScheduledExecutorService task = new OneTimeScheduledExecutorService();//一次性延时任务 public void checkStatus() { if (添加条件) { if (!task.containsTask(taskName)) { Runnable run = new DelayTask(参数); long delay = xxx task.schedule(taskName, run, delay, TimeUnit.MINUTES); } } else {取消 if (task.containsTask(taskName)) { task.shutdownNow(taskName); } } } /** * 任务 * * @author shay_deng * @since: v1.0 */ class DelayTask implements Runnable { public DelayTask(参数) { } @Override public void run() { 执行 } } }