spring boot 2.0 quartz 轻松实现定时任务和作业调度

简介: spring boot 2.0 quartz 轻松实现定时任务和作业调度

作者|olive丶

来源|

https://blog.csdn.net/asd1098626303/article/details/80831114


最近在做一个彩票相关的项目,主要涉及到不定时开奖,不定时封盘,原本打算使用springboot 自带的Schedule进行这一系列的工作,由于不能自动的添加定时任务,所以使用quartz,spring boot 2.0集成了quartz,所以决定尝试下quartz用于实现作业调度。

做的时候查看了很多资料,都写的花里胡哨的,要么就是做的东西太完整了,要么就是完全不能理解,要么就是很早以前的做法了,让人很头晕,所以说做个很简单明了的教程,说一下如何使用

https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#boot-features-quartz

build.gradle:

uildscript {

       ext  {

              springBootVersion  = '2.0.3.RELEASE'

       }

       repositories  {

              maven{  url 'http://maven.aliyun.com/nexus/content/groups/public'}

       }

       dependencies  {

              classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")

       }

}

apply plugin: 'java'

apply plugin: 'idea'

apply plugin: 'org.springframework.boot'

apply plugin: 'io.spring.dependency-management'

group = 'com.zhu'

version = '0.0.1-SNAPSHOT'

sourceCompatibility = 1.8

repositories {

       maven{  url 'http://maven.aliyun.com/nexus/content/groups/public'}

}

dependencies {

       compile('org.springframework.boot:spring-boot-starter-web')

       compile('org.springframework.boot:spring-boot-starter-quartz')

       testCompile('org.springframework.boot:spring-boot-starter-test')

}

build.gradle中引入spring-boot-starter-quartz

之后如果没什么特殊需求的话,根本不需要任何的花里胡哨的配置,直接编码。

创建 ScheduleService.java,用于创建定时任务,这里动态的创建了两个定时任务,每隔1秒和每隔2秒运行。创建时需要新建JobDetail(任务)以及CronTrigger(定时任务触发器) ,并且scheduler.scheduleJob(jobDetail,cronTrigger);把任务添加到任务队列中。

package com.zhu.zqjc.schedule;

import  com.zhu.zqjc.bean.enums.FootballStatus;

import com.zhu.zqjc.dao.FootBallMatchDao;

import com.zhu.zqjc.entity.FootBallMatch;

import org.quartz.*;

import  org.springframework.beans.factory.annotation.Autowired;

import  org.springframework.stereotype.Service;

import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;

import  java.time.format.DateTimeFormatter;

import java.util.List;

@Service

public class ScheduleService {

     @Autowired

     private Scheduler scheduler;

     public void testScheduleTask() throws SchedulerException {

         for (int i = 1; i < 3; i++) {

         JobDetail jobDetail = JobBuilder.newJob(TestSchedule.class)

                 .withIdentity("updateMatch"+i, "updateMatch")

                .withDescription("定时比赛Id为"+i)

                .build();

         //cron表达式 表示每隔i秒执行

         CronScheduleBuilder scheduleBuilder =  CronScheduleBuilder.cronSchedule(String.format("0/%d * * * * ?  ",i))

                .withMisfireHandlingInstructionDoNothing();

         CronTrigger cronTrigger = TriggerBuilder.newTrigger()

                 .withIdentity("updateMatch"+i, "updateMatch")

                .withDescription("定时比赛Id为"+i)

                 .withSchedule(scheduleBuilder)

                 .startNow().build();

         scheduler.scheduleJob(jobDetail,cronTrigger);

         }

     }

}

TestSchedule.java 定时任务的执行类,在executeInternal函数中执行定时任务的逻辑

package com.zhu.zqjc.schedule;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.springframework.scheduling.quartz.QuartzJobBean;

public class TestSchedule  extends QuartzJobBean {

     /**

      * Execute the actual job. The job data map will already have been

      * applied as bean property values by execute. The contract is

      * exactly the same as for the standard Quartz execute method.

      *

      * @param context

      * @see #execute

      */

     @Override

     protected void executeInternal(JobExecutionContext context) throws  JobExecutionException {

         System.out.println("定时任务执行 " +  context.getJobDetail().getDescription());

     }

}

 

StartListen.java 执行定时任务

package com.zhu.zqjc.listener;

import  com.zhu.zqjc.bean.enums.FootballStatus;

import com.zhu.zqjc.conf.SystemConf;

import com.zhu.zqjc.dao.FootBallMatchDao;

import com.zhu.zqjc.entity.FootBallMatch;

import  com.zhu.zqjc.schedule.ScheduleService;

import com.zhu.zqjc.schedule.UpdateMatchSchedule;

import org.quartz.*;

import  org.springframework.beans.factory.annotation.Autowired;

import  org.springframework.beans.factory.annotation.Value;

import  org.springframework.boot.context.event.ApplicationReadyEvent;

import org.springframework.context.ApplicationListener;

import  org.springframework.stereotype.Component;

import weixin.popular.support.TokenManager;

import java.util.Arrays;

import java.util.List;

/**

 *  Created by zhu yingzhi on 2018/6/6.

 *  @author  yingzhi zhu

 *

 */

@Component

public class StartListen implements  ApplicationListener<ApplicationReadyEvent> {

     @Autowired

     private ScheduleService scheduleService;

     @Override

     public void onApplicationEvent(final ApplicationReadyEvent event) {

         try {

             scheduleService.testScheduleTask();

         } catch (Exception e) {

            e.printStackTrace();

         }

     }

}

运行效果:

目录
相关文章
|
4月前
|
监控 Java BI
《深入理解Spring》定时任务——自动化调度的时间管理者
Spring定时任务通过@Scheduled注解和Cron表达式实现灵活调度,支持固定频率、延迟执行及动态配置,结合线程池与异常处理可提升可靠性,适用于报表生成、健康检查等场景,助力企业级应用自动化。
|
5月前
|
NoSQL Java 调度
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
分布式锁是分布式系统中用于同步多节点访问共享资源的机制,防止并发操作带来的冲突。本文介绍了基于Spring Boot和Redis实现分布式锁的技术方案,涵盖锁的获取与释放、Redis配置、服务调度及多实例运行等内容,通过Docker Compose搭建环境,验证了锁的有效性与互斥特性。
485 0
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
|
8月前
|
Java Spring
使用 Spring Boot 多个定时任务阻塞问题的解决方案
我是小假 期待与你的下一次相遇 ~
461 5
|
8月前
|
存储 前端开发 Java
|
9月前
|
监控 Java 调度
SpringBoot中@Scheduled和Quartz的区别是什么?分布式定时任务框架选型实战
本文对比分析了SpringBoot中的`@Scheduled`与Quartz定时任务框架。`@Scheduled`轻量易用,适合单机简单场景,但存在多实例重复执行、无持久化等缺陷;Quartz功能强大,支持分布式调度、任务持久化、动态调整和失败重试,适用于复杂企业级需求。文章通过特性对比、代码示例及常见问题解答,帮助开发者理解两者差异,合理选择方案。记住口诀:单机简单用注解,多节点上Quartz;若是任务要可靠,持久化配置不能少。
869 4
|
资源调度 Java 调度
Spring Cloud Alibaba 集成分布式定时任务调度功能
定时任务在企业应用中至关重要,常用于异步数据处理、自动化运维等场景。在单体应用中,利用Java的`java.util.Timer`或Spring的`@Scheduled`即可轻松实现。然而,进入微服务架构后,任务可能因多节点并发执行而重复。Spring Cloud Alibaba为此发布了Scheduling模块,提供轻量级、高可用的分布式定时任务解决方案,支持防重复执行、分片运行等功能,并可通过`spring-cloud-starter-alibaba-schedulerx`快速集成。用户可选择基于阿里云SchedulerX托管服务或采用本地开源方案(如ShedLock)
466 1
|
Java 调度 Spring
Spring之定时任务基本使用篇
本文介绍了在Spring Boot项目中使用定时任务的基本方法。主要通过`@Scheduled`注解实现,需添加`@EnableScheduling`开启定时任务功能。文中详细解析了Cron表达式的语法及常见实例,如每秒、每天特定时间执行等。此外,还探讨了多个定时任务的执行方式(并行或串行)及其潜在问题,并留待后续深入讨论。
617 64
|
IDE Java 数据库连接
SpringBoot整合XXL-JOB【02】- 启动调度中心
本文介绍了如何初始化和配置XXL-JOB调度中心。首先,从GitHub或Gitee获取源码;接着,执行`tables_xxl_job.sql`脚本初始化数据库。然后,在IDE中打开项目并修改`application.properties`中的数据库连接和`accessToken`配置。完成配置后,启动`XxlJobAdminApplication`,访问http://localhost:8080/xxl-job-admin/进行登录。最后,简要介绍了调度中心的主要功能模块,包括运行报表、任务管理、调度日志、执行器管理和用户管理。下篇将通过实例演示如何使用XXL-JOB执行定时任务。
711 6
SpringBoot整合XXL-JOB【02】- 启动调度中心
|
Java BI 调度
Java Spring的定时任务的配置和使用
遵循上述步骤,你就可以在Spring应用中轻松地配置和使用定时任务,满足各种定时处理需求。
814 2
|
存储 Java API
简单两步,Spring Boot 写死的定时任务也能动态设置:技术干货分享
【10月更文挑战第4天】在Spring Boot开发中,定时任务通常通过@Scheduled注解来实现,这种方式简单直接,但存在一个显著的限制:任务的执行时间或频率在编译时就已经确定,无法在运行时动态调整。然而,在实际工作中,我们往往需要根据业务需求或外部条件的变化来动态调整定时任务的执行计划。本文将分享一个简单两步的解决方案,让你的Spring Boot应用中的定时任务也能动态设置,从而满足更灵活的业务需求。
1201 4