ScheduledExecutorService 给定时间执行任务

问题描述:业务中需要执行 给定时间的结算任务(在给定的时间只执行一次),每次执行结算任务的时间没有规律而言。
还是采用ScheduledExecutorService的方式执行定时任务,之前的文章有详细讲解ScheduledExecutorService的构造原理。
下面直接贴上代码,供学习讨论。

ScheduledExecutorService scheduledExecutorService= new ScheduledThreadPoolExecutor(1,
        new BasicThreadFactory.
        Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());

	 /**
     * 
     * @param settlementTimes 需要执行任务的时间集合
     */
public void scheduledWorkTask(Set<Long> settlementTimes){
        long nowTime = System.currentTimeMillis();
        Long minSettlementTime = minSettlementTime(nowTime, settlementTimes);
        if (minSettlementTime != null){
        	// schedule 在延迟多少毫秒后 只执行一次
            scheduledExecutorService.schedule(new Runnable() {
                @Override
                public void run() {
                // 这里使用try catch 保证定时任务不中断
                    try {
                    // 自己的代码逻辑
                    
                    // 执行此次定时任务 再定时还未执行的时间任务 递归的方式
                     scheduledWorkTask(settlementTimes);
                    }catch (Exception e){
                        log.error(e.getMessage(),e);
                    }
                }
            },minSettlementTime-nowTime,TimeUnit.MILLISECONDS);
        }
    }
    
	/**
     * 
     * @param nowTime 当前时间
     * @param settlementTimes 需要执行任务的时间集合
     * @return 求出比当前时间大的最小时间
     */
    public Long minSettlementTime(long nowTime, Set<Long> settlementTimes){
        if (settlementTimes.isEmpty()){
            return null;
        }
        Long min = Collections.min(settlementTimes);
        if (nowTime > min){
            settlementTimes.remove(min);
            return minSettlementTime(nowTime,settlementTimes);
        }else {
            return min;
        }
    }

希望我的代码,能帮你带来些思路!
您的点赞,是我更新的动力!
还请各位大佬,提出批评指正!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值