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();
}
}*/
}