定时任务调度

时间:2022-07-14 08:11:37

 

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * Description: 任务调度支持类 <br>
 * 当调度执行完或者中断都需要把该任务从任务调度池中删除掉, 这样是为了避免池中垃圾对象积累。 <br>
 * <br>
 * <code>
 * public void run() {<br>
 * <pre>// do something...</pre>
 * <pre>ScheduleProcessSupport.remove(key);</pre>
 * }
 * </code>
 * </p>
 * */
public class ScheduledSupport {
    
    private static Map<String, ScheduledFuture<?>> scheduleFutureMap = ScheduledProcessPool.INSTANCE.getPool();
    
    private static ScheduledExecutorService scheduledService = ScheduledThreadPool.INSTANCE.getPool();
    
    /**
     * <p>
     * Description: 获取任务调度
     * </p>
     * 
     * @param key
     *            主键
     * @return
     */
    private static ScheduledFuture<?> getScheduledFutrue(String key) {
        ScheduledFuture<?> future = scheduleFutureMap.get(key);
        removeScheduled(key);
        return future;
    }
    
    /**
     * <p>
     * Description: 取消任务调度
     * </p>
     * 
     * @param key
     */
    private static void cancelScheduled(String key) {
        ScheduledFuture<?> future = getScheduledFutrue(key);
        if (future != null && !future.isDone()) {
            future.cancel(true);
        }
    }
    
    /**
     * <p>
     * Description: 创建延迟任务
     * </p>
     * 
     * @param key
     *            主键
     * @param thread
     *            线程
     * @param delay
     *            延迟执行时间
     * @param timeUnit
     *            延迟参数的时间单位
     */
    public static void schedule(String key, Thread thread, long delay, TimeUnit timeUnit) {
        cancelScheduled(key);
        scheduleFutureMap.put(key, scheduledService.schedule(thread, delay, timeUnit));
    }
    
    /**
     * <p>
     * Description: 创建延迟任务
     * </p>
     * 
     * @param key
     *            主键
     * @param thread
     *            线程
     * @param delay
     *            延迟执行时间(单位:秒)
     */
    public static void scheduleDelaySeconds(String key, Thread thread, long delay) {
        schedule(key, thread, delay, TimeUnit.SECONDS);
    }
    
    /**
     * <p>
     * Description: 移除任务调度
     * </p>
     * 
     * @param key
     *            主键
     * @return
     */
    public static void removeScheduled(String key) {
        if (scheduleFutureMap.containsKey(key)) {
            Iterator<String> it = scheduleFutureMap.keySet().iterator();
            while (it.hasNext()) {
                if (it.next().equalsIgnoreCase(key)) {
                    it.remove();
                    break;
                }
            }
        }
    }
    
    /**
     * <p>
     * Description: 获取调度池容量
     * </p>
     * 
     * @return
     */
    public static int getScheduledPoolSize() {
        return scheduleFutureMap.size();
    }
}

 

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * <p>
 * Description: 任务调度池
 * </p>
 * */
public enum ScheduledProcessPool {
    INSTANCE;
    
    private Map<String, ScheduledFuture<?>> scheduledPool;
    
    /** 调度池初始容量 */
    private int initialCapacity = 50;
    
    private ScheduledProcessPool() {
        scheduledPool = new ConcurrentHashMap<String, ScheduledFuture<?>>(initialCapacity);
    }
    
    /**
     * <p>
     * Description: 获取任务调度池
     * </p>
     * 
     * @return
     */
    public Map<String, ScheduledFuture<?>> getPool() {
        return scheduledPool;
    }
}

 

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

/**
 * <p>
 * Description: 任务线程池
 * </p>
 * */
public enum ScheduledThreadPool {
    INSTANCE;
    
    /** 线程池初始容量 */
    private int corePoolSize = 50;
    
    private ScheduledExecutorService exec;
    
    private ScheduledThreadPool() {
        exec = Executors.newScheduledThreadPool(corePoolSize, new ThreadFactoryBuilder().setNamePrefix("VIVO-H5-Thread")
                .setDaemon(false).setPriority(Thread.MAX_PRIORITY).build());
    }
    
    /**
     * <p>
     * Description: 获取任务线程池
     * </p>
     * 
     * @return
     */
    public ScheduledExecutorService getPool() {
        return exec;
    }
}

 

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * <p>
 * Description: 自定义线程工厂
 * </p>
 * */
public class ThreadFactoryBuilder {
    
    private String namePrefix = null;
    
    private boolean daemon = false;
    
    private int priority = Thread.NORM_PRIORITY;
    
    public ThreadFactoryBuilder setNamePrefix(String namePrefix) {
        if (namePrefix == null) {
            throw new NullPointerException();
        }
        this.namePrefix = namePrefix;
        return this;
    }
    
    public ThreadFactoryBuilder setDaemon(boolean daemon) {
        this.daemon = daemon;
        return this;
    }
    
    public ThreadFactoryBuilder setPriority(int priority) {
        if (priority < Thread.MIN_PRIORITY) {
            throw new IllegalArgumentException(
                    String.format("Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY));
        }
        if (priority > Thread.MAX_PRIORITY) {
            throw new IllegalArgumentException(
                    String.format("Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY));
        }
        this.priority = priority;
        return this;
    }
    
    public ThreadFactory build() {
        return build(this);
    }
    
    private static ThreadFactory build(ThreadFactoryBuilder builder) {
        final String namePrefix = builder.namePrefix;
        final Boolean daemon = builder.daemon;
        final Integer priority = builder.priority;
        final AtomicLong count = new AtomicLong(0);
        return new ThreadFactory() {
            
            @Override
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable);
                if (namePrefix != null) {
                    thread.setName(namePrefix + "-" + count.getAndIncrement());
                }
                if (daemon != null) {
                    thread.setDaemon(daemon);
                }
                if (priority != null) {
                    thread.setPriority(priority);
                }
                return thread;
            }
        };
    }
}