Java定时任务多线程实现问题的一个分析

本文介绍了一种定时任务系统的两种实现方案。第一种方案利用线程池实现任务的启动与停止,但存在线程资源占用过多的问题。第二种方案采用定时器扫描数据库并使用队列来调度任务,减少了线程资源的消耗。

1.最近参与的项目,设计了一套定时任务系统,实现如下:

1.初始化任务
 ScheduledFuture<?> future = threadPoolTaskScheduler.schedule((Runnable) Class.forName(cron.getCronClass()).newInstance(), new CronTrigger(cron.getCron()));
/**
 * 存放已经启动的任务map
 */
private final Map<String, ScheduledFuture<?>> scheduledFutureMap = new ConcurrentHashMap<>();

此时已经实现了定时任务的启停和动态周期,接着把启动的定时任务对象保存到map中,key为库中的name,value为ScheduledFuture对象,方便下次根据key获取到对象进行定时任务的停止。

  ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(getRunnable(scheduledTask), getTrigger(scheduledTask));

其中2个方法比较重要

读取配置中的要执行类名,并根据类名获取bean,进行调用
private Runnable getRunnable(ScheduleConfig config) {
    return new Runnable() {
        @Override
        public void run() {
            Class<?> clazz;
            try {
                clazz = Class.forName(config.getClassName());
                String className = lowerFirstCapse(clazz.getSimpleName());
                Object bean = ApplicationContextHelper.getBean(className);
                Method method = ReflectionUtils.findMethod(bean.getClass(), config.getMethod());
                ReflectionUtils.invokeMethod(method, bean);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    };
}


读取配置中的表达式
private Trigger getTrigger(ScheduleConfig scheduleConfig) {
    return new Trigger() {
        @Override
        public Date nextExecutionTime(TriggerContext triggerContext) {
            CronTrigger trigger = new CronTrigger(scheduleConfig.getTaskCron());
            Date nextExec = trigger.nextExecutionTime(triggerContext);
            return nextExec;
        }
    };

}


ApplicationContextHelper实现如下:
@Component
public class ApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public ApplicationContextHelper() {
    }

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

    public static Object getBean(String beanName) {
        return applicationContext != null?applicationContext.getBean(beanName):null;
    }
}

实现起来,动态加载,实时可以进行增删改查,没问题,但是领导提了一点,你这个如果有100个运行的任务,那么就有100个线程了,这样占资源太多了,能不能修改下,只有1或者2个常驻线程?

 

2.根据这个思路,我换了一种实现方法:

  1.  使用Timer定时器,定时扫描数据库,为了方式扫描调用数据库频繁,放到缓存中
  2.  主要是获取到是启动状态的,获取表达式,解析表达式,对比下次执行时间
  3. 1分钟执行一次,对比下次时间跟当前时间,分钟数小于1,则加入队列中
  4. 定时器扫描队列1分钟一次,从队列中获取到配置,那么就调用执行方法,执行任务
  5. 执行方法使用的是反射实现,配置项存储调用类,方法名,进行调用
 /**
     * 程序启动时初始化
     */

    public void initAllTask() {
        //3秒后开始执行,每隔一分钟执行一次
        Timer timer = new Timer();
        timer.schedule(new MainTimerTask(taskDao), 3 * 1000, 60 * 1000);
    }

 

public class MainTimerTask extends TimerTask {

    private static final String LIST_NAME = "taskConfigVOList";
    private static TaskConfigQueue taskConfigQueue;
    private final ScheduledTaskDao taskDao;
    List<TaskConfigVO> voList;

    public MainTimerTask(ScheduledTaskDao taskDao) {
        this.taskDao = taskDao;
    }


    @Override
    public void run() {
        voList = new ArrayList<>(16);
        if (CacheUtil.checkCache(LIST_NAME)) {
            voList = (List<TaskConfigVO>) CacheUtil.getCache(LIST_NAME);
        } else {
            voList = taskDao.getAllNeedStartTask();
        }
        List<String> names = new ArrayList<>(16);
        for (TaskConfigVO scheduledTask : voList) {
            if (CronSequenceGenerator.isValidExpression(scheduledTask.getTaskCron())) {
                CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(scheduledTask.getTaskCron());
                Date currentTime = new Date();
                // currentTime为计算下次时间点的开始时间
                Date nextTimePoint = cronSequenceGenerator.next(currentTime);
                double distanceMin = DateUtils.getDistanceMin(currentTime, nextTimePoint);
//                log.debug("当前时间为[{}],下次执行时间为[{}],时间差为{}分钟", DateUtils.formatDateTime(currentTime), DateUtils.formatDateTime(nextTimePoint), distanceMin);

                if (distanceMin < 1) {
//                    log.debug("时间已到,将任务[{}]存入队列", scheduledTask.getTaskName());
                    names.add(scheduledTask.getTaskName());
                    TaskConfigQueue.getInstance().offer(scheduledTask);
                }
            } else {
                log.error("{}表达式格式不对", scheduledTask);
            }
        }
        if (names.size() > 0) {
            log.debug("扫描结束,如下任务存入队列中即将执行,{}", names.toString());
        }


    }


}
public class TaskConfigQueue {
    private static BlockingQueue<TaskConfigVO> blockingQueue;
    private static TaskConfigQueue taskConfigQueue;

    private TaskConfigQueue() {
        // 规定BlockingQueue的容量
        blockingQueue = new LinkedBlockingQueue<TaskConfigVO>(100);
    }

    public static TaskConfigQueue getInstance() {
        if (taskConfigQueue == null) {
            synchronized (TaskConfigQueue.class) {
                if (taskConfigQueue == null) {
                    taskConfigQueue = new TaskConfigQueue();
                }
            }
        }
        return taskConfigQueue;
    }

    /**
     * 查看当前BlockingQueue的容量
     */
    public int getTaskConfigVol() {
        if (blockingQueue != null) {
            return blockingQueue.size();
        }
        return 0;
    }

    /**
     * 向BlockingQueue中放入指定的对象
     */
    public void put(TaskConfigVO taskConfigVO) {
        try {
            blockingQueue.put(taskConfigVO);
        } catch (InterruptedException e) {
            log.error("向队列放入对象[{}]发生异常[{}]", taskConfigVO, e);
        }
    }

    /**
     * 向BlockingQueue中放入指定的对象
     *
     * @param taskConfigVO TaskConfigVO
     */
    public void offer(TaskConfigVO taskConfigVO) {
        try {
            blockingQueue.offer(taskConfigVO, 2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("向队列放入对象[{}]发生异常[{}]", taskConfigVO, e);
        }
    }

    /**
     * 从BlockingQueue中提取指定对象
     *
     * @return TaskConfigVO
     */
    public TaskConfigVO take() {
        try {
            return blockingQueue.take();
        } catch (InterruptedException e) {
            log.error("向队列提取指定对象发生异常[{}]", e.getMessage());
        }
        return null;
    }

    /**
     * 从BlockingQueue中提取指定对象
     *
     * @return TaskConfigVO
     */
    public TaskConfigVO poll() {
        TaskConfigVO configVO = null;
        try {
            configVO = blockingQueue.poll(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("向队列提取指定对象发生异常[{}]", e.getMessage());
        }
        return configVO;
    }

}
public class Consumer {

    @Resource
    private TaskService taskService;

    /**
     * 此处使用了while循环,如果能获取到队列,则消费完后继续获取,
     * 当获取到队列的消息TaskConfigVO为null时,代表现在队列中已经已经没有消息,
     * 则跳出循环,60秒之后定时器再继续进行消费
     */
    @Scheduled(fixedDelay = 60000)
    public void consumerMessage() {
        boolean isRunning = true;
        while (isRunning) {
            TaskConfigVO configVO = TaskConfigQueue.getInstance().poll();
            if (null != configVO) {
                log.debug("获取到消息,开始执行任务[taskName={}]", configVO.getTaskName());
                taskService.initTask(configVO);
            } else {
                isRunning = false;
            }
        }
    }
}
public class CacheUtil {

    /**
     * 缓存对象
     */
    private static final ConcurrentHashMap<String, Object> CACHE_OBJECT_MAP = new ConcurrentHashMap<>();

    private static final Logger LOGGER = LoggerFactory.getLogger(CacheUtil.class);

    /**
     * 当前缓存个数
     */
    private static final Integer CURRENT_SIZE = 0;

    /**
     * 设置缓存
     */
    public static void setCache(String cacheKey, Object cacheValue) {
        if (cacheValue == null) {
            CACHE_OBJECT_MAP.put(cacheKey, "null");
            LOGGER.debug("have set key :{},value is null", cacheKey);
        } else {
            CACHE_OBJECT_MAP.put(cacheKey, cacheValue);
        }

        LOGGER.debug("have set key :{}", cacheKey);
    }
}

    /**
     * 调用实现类
     */
    public void initTask(TaskConfigVO config) {

        try {
            // 这里通过反射调用方法,带入ScheduleConfigBO的参数
            Class<?> clazz = Class.forName(config.getClassName());
            String className = lowerFirstCapse(clazz.getSimpleName());
            Object bean = ApplicationContextHelper.getBean(className);
            assert bean != null;
            Method method_args = ReflectionUtils.findMethod(bean.getClass(), EXECUTE_METHOD, TaskConfigVO.class);
            Method method = ReflectionUtils.findMethod(bean.getClass(), EXECUTE_METHOD);
            if (method_args != null) {
                log.debug("invoke method [{}] with args [{}]", EXECUTE_METHOD, config);
                ReflectionUtils.invokeMethod(method_args, bean, config);
            } else if (method != null) {
                log.debug("invoke method [{}] without args", EXECUTE_METHOD);
                ReflectionUtils.invokeMethod(method, bean);
            } else {
                log.error("method [{}] not found in class [{}]", EXECUTE_METHOD, config.getClassName());
            }
        } catch (ClassNotFoundException e) {
            log.error("Class [{}] Not Found ", config.getClassName());
        }
    }

----

加上定时任务配置项信息,以及实现

@ApiModel(value = "定时任务对象", description = "定时任务对象")
public class TaskConfigVO extends BaseEntity {

    @ApiModelProperty(value = "定时任务名,唯一")
    private String taskName;
    /**
     * 任务描述
     */
    @ApiModelProperty(value = "任务描述")
    private String taskDesc;

    @ApiModelProperty(value = "任务表达式", example = "0 0 0 * * ?")
    private String taskCron;

    @ApiModelProperty(value = "定时任务状态,1:开启,0:关闭", example = "0")
    private Integer status;

    @ApiModelProperty(value = "任务类型,0:内部方法,1:外部URL(同步),2:外部URL(异步)")
    private Integer type;

    @ApiModelProperty(value = "调用类/接口地址")
    private String className;

    @ApiModelProperty(value = "需要调用外部的url地址")
    private String url;

    @ApiModelProperty(value = "获取响应的url地址,type=2时必填")
    private String getResponseUrl;

    @ApiModelProperty(value = "获取响应超时时间,默认5分钟")
    private String timeOut;

    @ApiModelProperty(value = "需要调用的请求(json)")
    private String request;

    @ApiModelProperty(value = "扩展属性,一般用于内部传参", hidden = true)
    private Map<String, String> extMap;
}
@Service
public class LockUserTask {

    @Resource
    private UserDao userDao;
    @Transactional
    public Object run(TaskConfigVO config) {
        log.error("LockUserTask starting ………………………………………………………………………………………………………………");
        List<String> userIds = new ArrayList<>();
        List<UserEntity> userVOList = userDao.queryAllUsers();
        if(CollectionUtils.isEmpty(userVOList)){
            log.error("LockUserTask userVOList is null");
            return null;
        }
        // 循环过滤出需要锁定的用户
        for(UserEntity vo:userVOList){
            Date createTime = vo.getCreatedTime();
            Date lastLoginTime = vo.getLastLoginTime();
            if(judgeAccountIsNeedLock(createTime,lastLoginTime)){
                userIds.add(vo.getUserId());
            }
        }
        // 如果需要锁定的账号不为空,则不需要处理用户锁定状态
        if(!CollectionUtils.isEmpty(userIds)){
            userDao.batchUpdateUserStatus(userIds);
        }
        return null;
    }

    /**
     * 判断用户是否锁定
     * @param createTime
     * @param lastLoginTime
     * @return true 需要锁定,false 不需要
     */
    private boolean judgeAccountIsNeedLock(Date createTime,Date lastLoginTime){
        double distanceDays = 0;
        Date now = new Date();
        if(null == lastLoginTime){
            distanceDays = DateUtils.getDistanceOfTwoDate(createTime,now);
        } else{
            distanceDays = DateUtils.getDistanceOfTwoDate(lastLoginTime,now);
        }
        // TODO 90 后面做成配置
        if(distanceDays>=90){
            return true;
        }
        return false;
    }
}

 

这样大家给评论下,上下哪种更好呢? 下面的常驻线程就2个,而且实现了队列,如果我需要修改定时任务配置,调接口的时候顺带刷新缓存就行了,不会频繁调用数据库查询

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值