使用DelayQueue的实现延时任务

1、背景

项目中经常会用到类似一些需要延迟执行的功能,比如缓存。java提供了DelayQueue来很轻松的实现这种功能。Delayed接口中的getDelay方法返回值小于等于0的时候,表示时间到达,可以从DelayQueue中通过take()方法取的到期的对象。到期对象是实现了Delayed的类。

2、demo

2.1 依赖配置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2.2 整体架构

在这里插入图片描述

工具类TaskBase:
执行任务所需的基础参数

import lombok.Data;

@Data
public class TaskBase {
    //任务参数,根据业务需求多少都行
    private Long identifier;
 
    public TaskBase(Long identifier) {
        this.identifier = identifier;
    }
}

执行的任务和时间DelayTask

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延时任务
 */
public class DelayTask implements Delayed {
    //任务参数
    final private TaskBase data;
    //任务的延时时间,单位天
    final private long startTime;
 
    /**
     * 构造延时任务
     *
     * @param data 业务数据
     */
    public DelayTask(TaskBase data) {
        super();
        this.data = data;
        this.startTime = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3);
    }
    /**
     * 取消延时任务
     *
     * @param data   业务数据
         * @param startTime 任务延时时间(ms)
     */
    public DelayTask(TaskBase data,long startTime) {
        super();
        this.data = data;
//        this.expire = expire + System.currentTimeMillis();
        this.startTime = System.currentTimeMillis() + startTime;
    }
    public TaskBase getData() {
        return data;
    }
 
    public long getExpire() {
        return startTime;
    }
 
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof DelayTask) {
            return this.data.getIdentifier().equals(((DelayTask) obj).getData().getIdentifier());
        }
        return false;
    }
 
    @Override
    public String toString() {
        Date dNow = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(dNow);
        return "{" + "data:" + data.toString() + "," + "延时时间:" +startTime+ time + "}";
    }
 
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(startTime - System.currentTimeMillis(), unit);

//        return unit.convert(this.expire - System.currentTimeMillis(), unit);
    }
 
    @Override
    public int compareTo(Delayed o) {
        long delta = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return (int) delta;
    }
}

任务管理器DelayQueueManager:

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.byd.common.db.entity.Observe;
import com.byd.common.db.entity.Problem;
import com.byd.common.db.mapper.ObserveMapper;
import com.byd.common.db.mapper.ProblemMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class DelayQueueManager implements CommandLineRunner {
    @Autowired
    private ObserveMapper observeMapper;
    @Autowired
    private ProblemMapper problemMapper;
    private final Map<Long, DelayTask> elements = new HashMap<>();
    private final DelayQueue<DelayTask> delayQueue = new DelayQueue<>();
 
 
    /**
     * 加入到延时队列中
     * @param task
     */
    public void put(DelayTask task) {
        log.error("加入延时任务:{}", task);
        delayQueue.put(task);
        elements.put(task.getData().getIdentifier(),task);
    }
 
    /**
     * 取消延时任务
     *
     * @param task
     * @return
     */
    public boolean remove(DelayTask task) {
        log.error("取消延时任务:{}", task);
        return delayQueue.remove(task);
    }
    /**
     * 查询延时任务
     * @param taskID
     * @return
     */
    public DelayTask query(Long taskID) {
        return elements.get(taskID);
    }
    /**
     * 取消延时任务
     * @param taskid
     * @return
     */
    public boolean remove(Long taskid) {
        return remove(new DelayTask(new TaskBase(taskid),0));
    }
 
    @Override
    public void run(String... args) throws Exception {
        log.info("初始化延时队列");
        Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
    }
 
    /**
     * 延时任务执行线程
     */
    private void excuteThread() {
        while (true) {
            try {
                DelayTask task = delayQueue.take();
                //执行任务
                processTask(task);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
 
    /**
     * 内部执行延时任务
     *
     * @param task
     */
    private void processTask(DelayTask task) {
        //获取任务参数,执行业务task.getData().getIdentifier()
        log.error("执行延时任务:{}-{}", task, task.getData().getIdentifier());
    }
}

2.3 进行测试

import com.example.demo.task.DelayQueueManager;
import com.example.demo.task.DelayTask;
import com.example.demo.task.TaskBase;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
@SpringBootTest
class DemoApplicationTests {
    @Autowired
    private DelayQueueManager delayQueueManager;
 
    @Test
    void contextLoads() throws InterruptedException {
        Long problemId=Long.valueOf(2);
       //1、如果之前已存在延时任务则删除
        if(delayQueueManager.query(problemId)!=null){
            delayQueueManager.remove(problemId);
        }
        //2、新增任务
        delayQueueManager.put(new DelayTask(new TaskBase(problemId)));

    }
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中的Delay Queue延时队列)是一种用于处理延时任务的机制。延时任务指的是需要在一定时间后才能执行的任务。 Spring Boot中延时队列的实现主要借助了Spring的TaskScheduler来实现。TaskScheduler是Spring提供的任务调度器,可以用来执行延时任务。 为了使用延时队列,我们首先需要配置一个TaskScheduler。可以通过在配置类中添加@Bean注解来创建一个TaskScheduler的Bean。配置类内容如下: ``` @Configuration public class AppConfig { @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(5); scheduler.setThreadNamePrefix("TaskScheduler-"); return scheduler; } } ``` 上述配置创建了一个线程池大小为5的TaskScheduler对象,并且设置了线程名称前缀为"TaskScheduler-"。 接下来,我们可以创建一个延时任务,通过在方法上添加@Scheduled注解,并设置fixedDelay属性来定义延时的时间间隔,单位为毫秒。例如: ``` @Component public class DelayedTask { @Scheduled(fixedDelay = 5000) public void executeDelayedTask() { //延时任务的执行逻辑 System.out.println("执行延时任务"); } } ``` 上述代码中,executeDelayedTask方法使用@Scheduled注解来标识为定时任务,并设置fixedDelay为5000,表示延时5秒后执行任务。 最后,通过在启动类上添加@EnableScheduling注解来启用Spring的任务调度功能。即可实现延时任务的执行。 总结来说,Spring Boot中的Delay Queue延时队列)是通过配置TaskScheduler来实现的。我们可以通过在方法上添加@Scheduled注解,并设置fixedDelay属性来定义延时间隔,然后在启动类上添加@EnableScheduling注解来启用任务调度功能,从而实现延时任务的执行。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值