一个异步执行任务类

import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class TaskEngine {

	private static TaskEngine instance = new TaskEngine();

	private Timer timer;
	private ExecutorService executor;
	private Map<TimerTask, TimerTaskWrapper> wrappedTasks = new ConcurrentHashMap<TimerTask, TimerTaskWrapper>();

	public static TaskEngine getInstance() {
		return instance;
	}

	private TaskEngine() {
		timer = new Timer("timer", true);
		executor = Executors.newCachedThreadPool(new ThreadFactory() {
			final AtomicInteger threadNumber = new AtomicInteger(1);		
			public Thread newThread(Runnable runnable) {
				//Use our own naming scheme for the threads.
				Thread thread = new Thread(Thread.currentThread().getThreadGroup(), runnable,"pool-openfire" + threadNumber.getAndIncrement(), 0);
				//Make workers daemon threads.
				thread.setDaemon(true);
				if (thread.getPriority() != Thread.NORM_PRIORITY) {
					thread.setPriority(Thread.NORM_PRIORITY);
				}
				return thread;
			}
		});
	}

	public Future<?> submit(Runnable task) {
		return executor.submit(task);
	}

	public void schedule(TimerTask task, Date time) {
		timer.schedule(new TimerTaskWrapper(task), time);
	}

	public void schedule(TimerTask task, long delay) {
		timer.schedule(new TimerTaskWrapper(task), delay);
	}
	
	public void schedule(TimerTask task, Date firstTime, long period) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        wrappedTasks.put(task, taskWrapper);
        timer.schedule(taskWrapper, firstTime, period);
    }
	
	public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        wrappedTasks.put(task, taskWrapper);
        timer.scheduleAtFixedRate(taskWrapper, firstTime, period);
    }
	
	public void cancelScheduledTask(TimerTask task) {
        TaskEngine.TimerTaskWrapper taskWrapper = wrappedTasks.remove(task);
        if (taskWrapper != null) {
            taskWrapper.cancel();
        }
    }

	public void shutdown() {
		if (executor != null) {
			executor.shutdownNow();
			executor = null;
		}
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}

	private class TimerTaskWrapper extends TimerTask {

		private TimerTask task;

		public TimerTaskWrapper(TimerTask task) {
			this.task = task;
		}

		@Override
		public void run() {
			executor.submit(task);
		}
	}

}

猜你喜欢

转载自blog.csdn.net/tiandiqing/article/details/81110181
今日推荐