java使用延时队列实现定时任务,代码为模拟伪代码

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * 线程测试demo
 *
 * @author yang
 */
public class ThreadTest {
    /**
     * 定义信号量,许可证默认为0,异步线程默认阻塞等待,等待连接异常时发放许可证,进行登入操作
     */
    private static final Semaphore SEMAPHORE = new Semaphore(0);
    /**
     * 模拟放送报文状态, 1 失败 ,2 成功
     */

    private volatile static String result = "1";
    /**
     * 测试主线程退出状态,实际场景中不需要
     */
    private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);

    @Test
    public void test() throws Exception {
        //模拟测试,在实际场景中建议使用springboot @Async开启异步任务
        CompletableFuture.runAsync(() -> {
            try {
                //获取许可,若没有许可,一直等待
                SEMAPHORE.acquire();
                //将四个定时任务放入队列
                //前三次定时等待时间为1秒钟
                long firstTime = 1000;
                //第四个等待定时等待时间为5秒钟
                long secondTime = 5 * firstTime;
                //将四个定时任务放入延时队列
                List<MyDelay> delayList = Arrays.asList(new MyDelay(firstTime), new MyDelay(firstTime), new MyDelay(firstTime), new MyDelay(secondTime));
                DelayQueue<MyDelay> delayQueue = new DelayQueue<>(delayList);
                //队列不为空不退出循环,此场景永远不退出
                while (!delayQueue.isEmpty()) {
                    if (!"1".equals(result)) {
                        //发送成功,退出循环,等待信号量发送许可(连接异常时重新进入循环)
                        //清除队列,等待下次重新入列
                        delayQueue.clear();
                        System.out.println("发送报文成功");
                        COUNT_DOWN_LATCH.countDown();
                        break;
                    }
                    //模拟发送失败,等待延时队列任务,继续发送报文
                    MyDelay take = delayQueue.take();
                    System.out.println(take.getDelay(TimeUnit.MILLISECONDS));
                    //若一轮(4个)定时任务结束,重新放入四个
                    if (delayQueue.isEmpty()) {
                        //重新放入队列
                        delayList = Arrays.asList(new MyDelay(firstTime), new MyDelay(firstTime), new MyDelay(firstTime), new MyDelay(secondTime));
                        delayQueue = new DelayQueue<>(delayList);
                    }
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        //模拟连接状态异常
        Thread.sleep(10 * 1000);
        //发送许可(模拟连接状态异常)
        SEMAPHORE.release(1);
        //模拟发送报文成功
        Thread.sleep(20 * 1000);
        result = "2";
        //主线程等待,在实际业务场景中不需要
        COUNT_DOWN_LATCH.await();
    }
}

/**
 * 延时队列
 */
class MyDelay implements Delayed {
    /**
     * 延迟时长,这个是必须的属性因为要按照这个判断延时时长
     */
    long delayTime;


    public MyDelay(long delayTime) {
        this.delayTime = (System.currentTimeMillis() + delayTime);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(delayTime - System.currentTimeMillis(), unit);
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
延时队列定时任务的区别在于,延时队列是按照元素添加的时间来进行排序,而定时任务是按照预定的时间来触发执行的。延时队列可以用于实现某些需要延迟处理的业务场景,例如延迟发布、延迟重试等场景,而定时任务则适用于需要周期性执行任务的场景。 下面是使用Java实现延时队列的示例代码: ``` import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class DelayQueueDemo { public static void main(String[] args) { DelayQueue<DelayedElement> delayQueue = new DelayQueue<>(); delayQueue.offer(new DelayedElement("A", 3000)); delayQueue.offer(new DelayedElement("B", 2000)); delayQueue.offer(new DelayedElement("C", 1000)); while (!delayQueue.isEmpty()) { try { DelayedElement element = delayQueue.take(); System.out.println(element.getData() + "被取出,时间为:" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } } class DelayedElement implements Delayed { private String data; private long expireTime; public DelayedElement(String data, long delayTime) { this.data = data; this.expireTime = System.currentTimeMillis() + delayTime; } public String getData() { return data; } @Override public long getDelay(TimeUnit unit) { return unit.convert(expireTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS)); } } ``` 在这个示例中,我们定义了一个`DelayedElement`类,它实现了`Delayed`接口,并重了`getDelay`和`compareTo`方法。`getDelay`方法返回该元素离过期时间还有多少时间,`compareTo`方法用于比较两个元素的顺序。 在`main`方法中,我们首先创建了一个`DelayQueue`对象,并向其中添加了三个元素,分别延时1秒、2秒和3秒。然后我们不断从队列中取出元素,直到队列为空。在取出元素的过程中,由于是按照元素到期时间来排序的,所以最先到期的元素会被最先取出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值