Springboot定时任务的两种方式

本文介绍了SpringBoot内置的定时任务解决方案适用于小型单体项目,而Quartz则适合分布式场景,提供了更灵活的配置和并发控制。重点讨论了两者在任务执行和集群支持上的差异。
摘要由CSDN通过智能技术生成

第一种简单,适合小型单体项目跑批,第二种适合分布式项目

一、Spring自带

直接以代码说明,就是这么简单,这就可以了,主要是cron表达式

package com.htao.train.batch.job;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
* 适合单体应用,不适合集群
* 没法实时更改定时任务状态和策略
*/
@Component
@EnableScheduling
public class SpringBootTestJob {

 @Scheduled(cron = "0/5 * * * * ?")
 private void test() {
     // 增加分布式锁,解决集群问题
     System.out.println("SpringBootTestJob TEST");
 }
}

二、quartz

1.引入依赖
2.写任务类,需要实现接口
3.配置类

1.依赖

springboot指定了版本,因此无需再次指定

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

2.写任务类,需要实现接口

package com.htao.train.batch.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * @Author: HTTT
 * @Date: 2024/1/8 21:53
 * @Describe:
 */
public class TestJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("test job");
    }
}

3.配置类

声明任务和触发器

package com.htao.train.batch.config;

import com.htao.train.batch.job.TestJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {

 /**
  * 声明一个任务
  * @return
  */
 @Bean
 public JobDetail jobDetail() {
     return JobBuilder.newJob(TestJob.class)
             .withIdentity("TestJob", "test")
             .storeDurably()
             .build();
 }

 /**
  * 声明一个触发器,什么时候触发这个任务
  * @return
  */
 @Bean
 public Trigger trigger() {
     return TriggerBuilder.newTrigger()
             .forJob(jobDetail())
             .withIdentity("trigger", "trigger")
             .startNow()
             .withSchedule(CronScheduleBuilder.cronSchedule("*/2 * * * * ?"))
             .build();
 }
}

并发执行

默认并发,即不管上一个执行完没有 直接执行下一个

取消并发需要加注解,加的话代表,等上一个任务执行完,并且下一个任务该执行了就执行

@DisallowConcurrentExecution
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值