自定义定时线程池的封装

package pk.shoplus.vendor.controller.restful;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

/**
 * 自定义定时线程池
 * @author yfding
 *
 */
public class ThreadPoolTimer {
	private static final Logger logger = Logger.getLogger(ThreadPoolTimer.class);
	
	// the number of threads to keep in the pool, even if they are idle.
	public static ScheduledExecutorService scheduExec = Executors.newScheduledThreadPool(3);
	
	public static final ThreadPoolTimer threadPoolTimer = new ThreadPoolTimer();
	
	private static final Long initialDelay = 10L;// 10L;
	
	private static final Long period = 60*3L;// ;
	
	public static ThreadPoolTimer getInstance(){
		if(threadPoolTimer == null)
			return new ThreadPoolTimer();
		return threadPoolTimer;
	}
	
	/**
	 * 
	 * @param task 要执行的任务
	 * @param initialDelay 首次执行要延迟的时间
	 * @param period 一次执行终止和下一次执行开始之间的延迟
	 */
	@Deprecated
	private void executeTask(Runnable task,Long initialDelay,Long period){
		scheduExec.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
	}
	
	public void executeTask(List<Runnable> tasks){
		try {
			if(tasks != null && tasks.size() > 0) {
				for(Runnable task : tasks) {
					scheduExec.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("ThreadPoolTimer ErrorMessage:" + e.getMessage());
		}
	}
	
	public void executeTask(Runnable task){
		try {
			scheduExec.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("ThreadPoolTimer ErrorMessage:" + e.getMessage());
		}
	}
	
	public void destory(){
		if (scheduExec != null)
			scheduExec.shutdown();
	}
	
	/*public static void main(String[] args) {
		ThreadPoolTimer.getInstance().executeTask(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("A");
			}
		},1L,1L);
		
		ThreadPoolTimer.getInstance().executeTask(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("B");
			}
		},1L,1L);
		
		try {
			Thread.sleep(10000);
			System.out.println("shutdown");
			ThreadPoolTimer.getInstance().destory();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/
}

 

转载于:https://my.oschina.net/u/3465537/blog/907116

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值