Delay Task : Thread « Development « Android






Delay Task

    
/**
 * @(#)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<String, ScheduledFuture<Runnable>> taskHandles = new ConcurrentHashMap<String, ScheduledFuture<Runnable>>();

  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<Runnable> taskHandle = taskHandles.get(taskId);
    if (taskHandle == null || taskHandle.isDone()) {
      taskHandle = (ScheduledFuture<Runnable>) scheduler.schedule(task, delay, unit);
    } else {
      taskHandle.cancel(true);
      taskHandle = (ScheduledFuture<Runnable>) scheduler.schedule(task, delay, unit);
    }
    taskHandles.put(taskId, taskHandle);
  }

  /**
   * ???????????
   * @param taskId ??Id
   */

  public void cancel(String taskId) {
    ScheduledFuture<Runnable> taskHandle = taskHandles.get(taskId);
    if (taskHandle != null && !taskHandle.isDone()) {
      taskHandle.cancel(true);
    }
  }

  /**
   * ???????????
   */

  public void cancelAllTask() {
    for (String taskId : taskHandles.keySet()) {
      ScheduledFuture<Runnable> taskHandle = taskHandles.get(taskId);
      if (taskHandle != null && !taskHandle.isDone()) {
        taskHandle.cancel(true);
      }
    }
  }

  /**
   * ????????????????????????
   */
  public void shutdown() {
    scheduler.shutdown();
  }

}

   
    
    
    
  








Related examples in the same category

1.Threads Handler Demo
2.Abstract Running Thread
3.Sleep current thread
4.Executors.newFixedThreadPool
5.Counting Thread
6.Task Queue