threadPoolTask实现方式

 实现方式一:

package com.cashbang.module.schedule;

import com.cashbang.module.passport.common.DateUtil;
import org.anonymous.logger.Logger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * @Author: RenLiLi
 * @Date: 2019/1/24 17:01
 */
public class ScheduleUtil {
    private static Logger logger = Logger.getLogger(ScheduleUtil.class);

    private static ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    private static Map<String, ScheduledFuture<?>> schedutedFutureMap = new HashMap<>();

    static {
        threadPoolTaskScheduler.setPoolSize(20);
        threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskScheduler.initialize();
        logger.info("定时任务线程池启动");
    }

    /**
     * 启动某定时任务
     * @param scheduledTask
     * @param startTime
     */
    public static void start(ScheduledTask scheduledTask, Date startTime){
        ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.schedule(scheduledTask, startTime);
        schedutedFutureMap.put(scheduledTask.getId(),scheduledFuture);
        logger.info("启动定时任务" + scheduledTask.getId() + ",执行时间为" + DateUtil.formatterDate(startTime, "yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 取消某定时任务
     * @param taskId
     */
    public static void cancel(String taskId) {
        ScheduledFuture<?> scheduledFuture = schedutedFutureMap.get(taskId);
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(true);
        }
        schedutedFutureMap.remove(taskId);
        logger.info("取消定时任务" + taskId + ",取消时间为" + DateUtil.formatterDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 取消某个任务 重新开启新任务
     * @param oldTaskId
     * @param startTime
     * @param newtaskId
     */
    public static void reset(String oldTaskId, Date startTime, String newtaskId){
        ScheduledFuture<?> scheduledFuture = schedutedFutureMap.get(oldTaskId);
        if(scheduledFuture != null && !scheduledFuture.isCancelled()){
            scheduledFuture.cancel(true);
        }
        schedutedFutureMap.remove(oldTaskId);
        //然后启动信的定时任务
        ScheduledTask newScheduleTask = new ScheduledTask(newtaskId);
        scheduledFuture = threadPoolTaskScheduler.schedule(newScheduleTask, startTime);
        schedutedFutureMap.put(newScheduleTask.getId(), scheduledFuture);
        logger.info("启动定时任务" + newScheduleTask.getId() + "的执行时间为" + DateUtil.formatterDate(startTime, "yyyy-MM-dd HH:mm:ss"));
    }

    public static void aa(){
        System.out.println("当前active线程数:" +threadPoolTaskScheduler.getActiveCount());
    }
}






package com.cashbang.module.schedule;

import com.cashbang.module.passport.common.DateUtil;
import com.cashbang.module.warn.common.CheckBalanceRemind;
import org.anonymous.logger.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: RenLiLi
 * @Date: 2019/1/24 17:37
 */
public class ScheduledTask implements Runnable {

    private static Logger logger = Logger.getLogger(ScheduledTask.class);

    /**
     * 任务唯一标识
     */
    protected String id;

    public String getId() {
        return id;
    }

    public ScheduledTask(String id) {
        this.id = id;
    }

    @Override
    public void run() {
        logger.info(id + "开始执行,时间:"+ DateUtil.formatterDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
        CheckBalanceRemind checkBalanceRemind = (CheckBalanceRemind) SpringContextUtils.getBeanByClass(CheckBalanceRemind.class);
        checkBalanceRemind.balanceRemindTask(id);
    }

    public static void main(String [] args){
        try{
            logger.info("当前时间:"+ DateUtil.formatterDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
            ScheduledTask task1= new ScheduledTask("task1");
            ScheduleUtil.start(task1, DateUtil.addDateTime(new Date(), Calendar.MINUTE, 2));
            /*ScheduledTask task2= new ScheduledTask("task2");
            ScheduleUtil.start(task2, DateUtil.addDateTime(new Date(), Calendar.SECOND, 2));*/
           /* Thread.sleep(30000);
            ScheduleUtil.reset("task1", DateUtil.addDateTime(new Date(), Calendar.SECOND, 1), "task2");
            Thread.sleep(30000);
            ScheduleUtil.aa();*/
        }catch (Exception e){

        }
    }
}




package com.cashbang.module.schedule;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: RenLiLi
 * @Date: 2019/1/30 11:20
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext arg0)
            throws BeansException {
        applicationContext = arg0;
    }

    /**
     * 获取applicationContext对象
     * @return
     */
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    /**
     * 根据bean的id来查找对象
     * @param id
     * @return
     */
    public static Object getBeanById(String id){
        return applicationContext.getBean(id);
    }

    /**
     * 根据bean的class来查找对象
     * @param c
     * @return
     */
    public static Object getBeanByClass(Class c){
        return applicationContext.getBean(c);
    }

    /**
     * 根据bean的class来查找所有的对象(包括子类)
     * @param c
     * @return
     */
    public static Map getBeansByClass(Class c){
        return applicationContext.getBeansOfType(c);
    }
}

实现方式二:

package com.cashbang.api.schedule.controller;

import com.cashbang.module.passport.common.DateUtil;
import com.cashbang.module.schedule.ScheduledTask;
import com.cashbang.module.warn.common.CheckBalanceRemind;
import io.swagger.annotations.Api;
import org.anonymous.logger.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * @Author: RenLiLi
 * @Date: 2019/1/30 15:52
 */
@Component
public class DynamicTask {

    private static Logger logger = Logger.getLogger(DynamicTask.class);

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Autowired
    private CheckBalanceRemind checkBalanceRemind;

    private static Map<String, ScheduledFuture<?>> schedutedFutureMap = new HashMap<>();

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(20);
        executor.setAwaitTerminationSeconds(60);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

    /**
     * 启动某定时任务
     * @param taskId
     * @param startTime
     */
    public void startCron(String taskId, Date startTime) {
        ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.schedule(new MyRunnable(taskId), startTime);
        schedutedFutureMap.put(taskId, scheduledFuture);
        logger.info("DynamicTask.startCron():taskId={}, startTime={}", taskId, DateUtil.formatterDate(startTime, "yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 取消某定时任务
     * @param taskId
     */
    public void stopCron(String taskId) {
        ScheduledFuture<?> scheduledFuture = schedutedFutureMap.get(taskId);
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
        }
        schedutedFutureMap.remove(taskId);
        logger.info("DynamicTask.stopCron():taskId={}", taskId);
    }

    /**
     * 取消某个任务 重新开启新任务
     * @param oldTaskId
     * @param startTime
     * @param newtaskId
     */
    public void restCron(String oldTaskId, Date startTime, String newtaskId) {
        // 先停止,在开启
        stopCron(oldTaskId);
        startCron(newtaskId, startTime);
        logger.info("DynamicTask.restCron(): 关闭taskId={},启动taskId={}startTime={}", oldTaskId, newtaskId, DateUtil.formatterDate(startTime, "yyyy-MM-dd HH:mm:ss"));
    }

    private class MyRunnable implements Runnable {
        private Logger logger = Logger.getLogger(MyRunnable.class);
        /**
         * 任务唯一标识
         */
        protected String id;

        public String getId() {
            return id;
        }

        public MyRunnable(String id) {
            this.id = id;
        }

        @Override
        public void run() {
            logger.info("DynamicTask.MyRunnable.run() taskId={})", id);
            checkBalanceRemind.balanceRemindTask(id);
        }
    }

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值