基于Netty的HashedWheelTimer实现延迟任务

package com.cmcc.open.ota.config;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DelayTaskDemo {
    public static void main(String[] args) {

        log.info("main start");
        TimerTask task = new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                log.info("延时任务开始执行咯。。。");
            }
        };
        runDelayTask(task, 10, TimeUnit.SECONDS);
    }

    private static final HashedWheelTimer timer = new HashedWheelTimer();

//最好是异步线程执行
public static void runDelayTask(TimerTask task, long delay, TimeUnit unit) { timer.newTimeout(task, delay, unit); } }

 

 

TestController模拟添加任务
private static final HashedWheelTimer timer = new HashedWheelTimer();
    
    @GetMapping("/addtask")
    public void addtask(HttpServletRequest request,
                        @RequestParam(value = "param") String param,
                        @RequestParam(value = "delay") long delay) {
        log.info("接受新任务param={},delay={}",param,delay);
        timer.newTimeout(task->{delayTaskDemo.asynDealWithBusiness(param);}, delay, TimeUnit.SECONDS);
    }

  

其中 异步执行的业务方法,delayTaskDemo.asynDealWithBusiness(param) 方法如下:

@Slf4j
@Component
public class DelayTaskDemo {
    
    @Async("asyncPoolTaskExecutor")
    public void asynDealWithBusiness(String args){
        log.info("任务开始执行args={}",args);
    }
}

  

netty的HashedWheelTimer 原理和源码简介:

https://segmentfault.com/a/1190000042473292?utm_source=sf-similar-article

 

posted @ 2023-01-17 19:44  乌云de博客  阅读(147)  评论(0编辑  收藏  举报