Java使用Spring Task 实现定时推送消息

Spring Task 实现定时推送消息

项目中需要执行一些定时任务,比如在凌晨时候更新一些新的信息,每天上午10:30定时发送消息通知等等

  1. 导入相关依赖
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
  </dependency>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>
  1. 创建定时任务
@Slf4j
@Component
public class ScheduledService {
    @Async
    @Scheduled(cron = " 0 30 10 ? * 1,2,3,4,5")  //周一到周五每天上午10:30
    public void scheduled(){
        //定时任务
        System.out.println("=====>>>>>使用cron  {}"+System.currentTimeMillis());
    }
    @Scheduled(fixedRate = 5000) //毫秒
    public void scheduled1() {
        System.out.println("=====>>>>>使用fixedRate{}"+System.currentTimeMillis());
    }
    @Scheduled(fixedDelay = 5000) //毫秒
    public void scheduled2() {
        System.out.println("=====>>>>>fixedDelay{}"+System.currentTimeMillis());
    }
}

主类使用@EnableScheduling注解开启对定时任务的支持,然后启动项目

执行时间的配置

在方法上使用@Scheduled注解来设置任务的执行时间,并且使用三种属性配置方式:

  1. fixedRate:定义一个按一定频率执行的定时任务
  2. fixedDelay:定义一个按一定频率执行的定时任务,与上面不同的是,改属性可以配合initialDelay, 定义该任务延迟执行时间。
  3. cron:通过表达式来配置任务执行时间

cron表达式详解

一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。按顺序依次为:

1. 秒(0~59)
2. 分钟(0~59)
3. 小时(0~23)
4. 天(0~31)
5. 月(0~11)
6. 星期(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
7. 年份(1970-2099)

在线cron表达式生成:http://qqe2.com/cron/index

问题

当运行一个定时任务是并没有什么问题, 但是当多线程并发执行, 如果其中一个任务出现问题, 会导致其他任务也无法正常运行

解决办法(多线程执行)

使用config配置类的方式添加配置

@Configuration
@EnableAsync
public class AsyncConfig {
     /*
    此处成员变量应该使用@Value从配置中读取
     */
    private int corePoolSize = 10;
    private int maxPoolSize = 200;
    private int queueCapacity = 10;
    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }
}

@Configuration:表明该类是一个配置类
@EnableAsync:开启异步事件的支持

然后在定时任务的类或者方法上添加@Async 。最后重启项目,每一个任务都是在不同的线程中

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java小鲤鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值