springboot定时任务

springboot定时任务

需求场景:一个消息通知系统,新建通知设定指定时间后自动发布。
需求分析:新建消息后数据存入数据库中,然后通过定时任务去触发发布事件。
实现①:新增后直接将该消息加入到定时任务的延迟队列当中,到时候后自动发布。
实现②:新增2个定时任务,定时任务1每隔 a 时间去数据库取出 b 时间内将要发布的通知(其中a<<b), 然后将其加入到定时任务2的延迟队列当中,到时间后自动发布。
对比:实现①是比较简单的实现,一般数据量不大的系统是没有什么太大问题的,实现②将定时任务2的队列设置一个阈值,控制延迟队列中的任务数量,因为延迟队列中需要对新加入的任务进行重排序,所以控制队列任务数量能够保持性能。
具体实现方案:定时任务的核心是利用java自带的定时任务类ScheduledThreadPoolExecutor,其提供了一个方法

/**
     * Creates and executes a one-shot action that becomes enabled
     * after the given delay.
     *
     * @param command the task to execute
     * @param delay the time from now to delay execution
     * @param unit the time unit of the delay parameter
     * @return a ScheduledFuture representing pending completion of
     *         the task and whose {@code get()} method will return
     *         {@code null} upon completion
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if command is null
     */
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);

其中参数command就是需要执行命令delay为延迟时间,unit为时间单位,
新建两个定时任务,分别是定时轮询任务A、定时消息通知任务BA任务每隔2分钟查看B任务中剩余的任务数量,若小于500个,则从数据库取出 适量的 5分钟内要发布的通知,然后将其加入到B任务中,完成定时发布。
简单的demo实现如下(不是实际代码):
Springboot工程结构
在这里插入图片描述
定时任务配置类 ScheduleConfig.java

package com.yuan.springboot.scheduledemo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframewo
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值