SpringBoot定时任务两种(Spring Schedule 与 Quartz 整合 )实现方法

2025-05-29 0 26

前言

最近在项目中使用到定时任务,之前一直都是使用Quartz 来实现,最近看Spring 基础发现其实Spring 提供 Spring Schedule 可以帮助我们实现简单的定时任务功能。

下面说一下两种方式在Spring Boot 项目中的使用。

Spring Schedule 实现定时任务

Spring Schedule 实现定时任务有两种方式 1. 使用XML配置定时任务, 2. 使用 @Scheduled 注解。 因为是Spring Boot 项目 可能尽量避免使用XML配置的形式,主要说注解的形式.

Spring Schedule 提供三种形式的定时任务

固定等待时间 @Scheduled(fixedDelay = 时间间隔 )

?

1

2

3

4

5

6

7

8

9

10

11

12
@Component

public class ScheduleJobs {

public final static long SECOND = 1 * 1000;

FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

@Scheduled(fixedDelay = SECOND * 2)

public void fixedDelayJob() throws InterruptedException {

TimeUnit.SECONDS.sleep(2);

System.out.println("[FixedDelayJob Execute]"+fdf.format(new Date()));

}

}

固定间隔时间 @Scheduled(fixedRate = 时间间隔 )

?

1

2

3

4

5

6

7

8

9

10

11
@Component

public class ScheduleJobs {

public final static long SECOND = 1 * 1000;

FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

@Scheduled(fixedRate = SECOND * 4)

public void fixedRateJob() {

System.out.println("[FixedRateJob Execute]"+fdf.format(new Date()));

}

}

Corn表达式 @Scheduled(cron = Corn表达式)

?

1

2

3

4

5

6

7

8

9

10

11
@Component

public class ScheduleJobs {

public final static long SECOND = 1 * 1000;

FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

@Scheduled(cron = "0/4 * * * * ?")

public void cronJob() {

System.out.println("[CronJob Execute]"+fdf.format(new Date()));

}

}

Spring Boot 整合 Quartz 实现定时任务

添加Maven依赖

?

1

2

3

4

5

6

7

8
<dependency>

<groupId>org.quartz-scheduler</groupId>

<artifactId>quartz</artifactId>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

</dependency>

Spring Boot 整合 Quartz

Spring 项目整合 Quartz 主要依靠添加 SchedulerFactoryBean 这个 FactoryBean ,所以在maven 依赖中添加 spring-context-support 。

首先添加 QuartzConfig 类 来声明相关Bean

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
@Configuration

public class QuartzConfig {

@Autowired

private SpringJobFactory springJobFactory;

@Bean

public SchedulerFactoryBean schedulerFactoryBean() {

SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();

schedulerFactoryBean.setJobFactory(springJobFactory);

return schedulerFactoryBean;

}

@Bean

public Scheduler scheduler() {

return schedulerFactoryBean().getScheduler();

}

}

这里我们需要注意 我注入了一个 自定义的JobFactory ,然后 把其设置为SchedulerFactoryBean 的 JobFactory。其目的是因为我在具体的Job 中 需要Spring 注入一些Service。

所以我们要自定义一个jobfactory, 让其在具体job 类实例化时 使用Spring 的API 来进行依赖注入。

SpringJobFactory 具体实现:

?

1

2

3

4

5

6

7

8

9

10

11

12

13
@Component

public class SpringJobFactory extends AdaptableJobFactory {

@Autowired

private AutowireCapableBeanFactory capableBeanFactory;

@Override

protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {

Object jobInstance = super.createJobInstance(bundle);

capableBeanFactory.autowireBean(jobInstance);

return jobInstance;

}

}

具体使用 (摘取自项目代码):

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
@Service

public class QuartzEventServiceImpl implements QuartzEventService {

private static final String JOB_GROUP = "event_job_group";

private static final String TRIGGER_GROUP = "event_trigger_group";

@Autowired

private Scheduler scheduler;

@Override

public void addQuartz(Event event) throws SchedulerException {

JSONObject eventData = JSONObject.parseObject(event.getEventData());

Date triggerDate = eventData.getDate("date");

JobDetail job = JobBuilder.newJob(EventJob.class).withIdentity(event.getId().toString(), JOB_GROUP).usingJobData(buildJobDateMap(event)).build();

Trigger trigger = TriggerBuilder.newTrigger().withIdentity(event.getId().toString(), TRIGGER_GROUP).startAt(triggerDate).build();

scheduler.scheduleJob(job, trigger);

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.cnblogs.com/javanoob/p/springboot_schedule.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 SpringBoot定时任务两种(Spring Schedule 与 Quartz 整合 )实现方法 https://www.kuaiidc.com/118036.html

相关文章

发表评论
暂无评论