当前位置: 移动技术网 > IT编程>开发语言>Java > 一种基于线程池进行定时调度的实现方案

一种基于线程池进行定时调度的实现方案

2020年07月17日  | 移动技术网IT编程  | 我要评论
前言实现定时调度的方案真的是太多了,此处实现经典的基于线程池的定时调度方案。具体实现1,编写调度线程管理类@Slf4j@Servicepublic class TimerTaskService { private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10, new ThreadFactory() {

前言

实现定时调度的方案真的是太多了,此处实现经典的基于线程池的定时调度方案。

具体实现

1,编写调度线程管理类

@Slf4j
@Service
public class TimerTaskService {

    private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10, new ThreadFactory() {
                AtomicInteger count = new AtomicInteger(0);
                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setDaemon(true);
                    t.setName("Timer-" + count.getAndIncrement());
                    return t;
                }
            });

    public static void scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,
                                              TimeUnit unit) {
        scheduledExecutorService.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    }

}

2,编写定时任务分发调度类

@Slf4j
@Service
public class TaskDispatchService implements Constant {

    @Value("${spring.profiles.active}")
    private String active;

    @Autowired
    private CheckMessageTask checkMessageTask;

    @Autowired
    private DelayMatchTask delayMatchTask;

    long DELAY_INTERVAL_SECONDS = 60*10;

    long CHECK_INTERVAL_SECONDS = 60*60;

    @PostConstruct
    public void init() {
        log.info("TaskDispatchService init success .....");
        if(!"prod".equals(active)) {
            DELAY_INTERVAL_SECONDS = 60*5;
            CHECK_INTERVAL_SECONDS = 60*5;
        }

        TimerTaskService.scheduleWithFixedDelay(delayMatchTask, 0L, DELAY_INTERVAL_SECONDS, TimeUnit.SECONDS);

        TimerTaskService.scheduleWithFixedDelay(checkMessageTask, 0L, CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS);
    }

}

3,编写具体的调度任务类

1)任务1: DelayMatchTask.java

@Slf4j
@Component
public class DelayMatchTask implements Runnable {

    @Autowired
    private SocialUserMatchMapper socialUserMatchMapper;

    @Autowired
    private SocialUserMatchService socialUserMatchService;

    @Override
    public void run() {
        int startRow = 0;
        int pageSize = 5;
        try {
            log.info("DelayMatchTask run start");
            UserMatchInfo umi = new UserMatchInfo();
            umi.setTipsFlag(0);
            umi.setTipsTime(System.currentTimeMillis()/1000);
            Map<String, Object> map = new HashMap<>();
            map.put("userMatchInfo", umi);
            map.put("startRow", startRow);
            map.put("pageSize", pageSize);
            boolean cycle = true;
            while (true) {
                if(!cycle) {
                    break;
                }
                List<UserMatchInfo> targetList = socialUserMatchMapper.queryMatchRoomNotTips(map);
                if(null == targetList || targetList.size() <= 0) {
                    break;
                } else if(targetList.size() < pageSize){
                    cycle = false;
                }
                for(UserMatchInfo userMatchInfo: targetList) {
                    try {
                        int count = socialUserMatchMapper.updateMatchRoom(userMatchInfo);
                        if (count > 1) {
                            socialUserMatchService.sendMatchSuccessMessage(userMatchInfo);
                        }
                    } catch (Exception e) {
                        log.error("run userMatchInfo:{} have exception:{}" , userMatchInfo, e.getLocalizedMessage());
                    }
                }
                startRow = startRow + pageSize;
            }
        } catch (Exception e) {
            log.error("run have exception:{}" , e);
        }
    }
}

2)任务2: CheckMessageTask.java

@Slf4j
@Component
public class CheckMessageTask implements Runnable,RedisConstant,Constant {

    @Autowired
    private JedisCluster jedisCluster;

    long RESERVED_LENGTH = 300;

    @Value("${spring.profiles.active}")
    private String active;

    @Override
    public void run() {
        try {
            log.info("CheckMessageTask run start");
            if(!"prod".equals(active)) {
                RESERVED_LENGTH = 50;
            }
            while (true) {
                String activeRoomKey = REDIS_SOCIAL_CURRENT_ACTIVE_ROOM_SET;
                long sLength = jedisCluster.scard(activeRoomKey);
                if(sLength <= 0) {
                    return;
                }
                TimeUnit.SECONDS.sleep(1);
                String roomId = jedisCluster.spop(activeRoomKey);
                handleSingle(roomId);
            }
        } catch (Exception e) {
            log.error("run have exception:{}" , e.getLocalizedMessage());
        }
    }

    private void handleSingle(String roomId) {
        String roomSetKey = String.format(REDIS_SOCIAL_ROOM_MESSAGE_ZSET, roomId);
        long length = jedisCluster.zcard(roomSetKey);
        log.info("roomSetKey:{} length:{}", roomSetKey, length);
        if(length <= RESERVED_LENGTH) {
            return;
        }
        long end = length - RESERVED_LENGTH - 1;
        if(end < 0) {
            return;
        }
        jedisCluster.zremrangeByRank(roomSetKey, 0, end);
    }

}

 

本文地址:https://blog.csdn.net/FENGQIYUNRAN/article/details/107343511

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网