使用Spring Boot来使用Quartz(1).

将Spring Boot与作业调度程序”Quartz”集成,并创建用于作业注册和删除的端点,然后执行。

■ 完成的想象

+----------+            +-------------+            +------------+
|          |            | Spring Boot |   JDBC     |   Job      |
| Browser |<---------->|     +       |<---------->| Persistent |
|          | port=8080  |   Quartz    | port=33060 |   data     |
|          |            |             |            |  (MySQL)   |
+----------+            +-------------+            +------------+

■建设环境

・Windows10 版本21H2
・IntelliJ IDEA 2022.1.4(社区版)
・OpenJDK 运行时环境 Zulu17.36+17-CA(版本 17.0.4.1+1-LTS)
・Spring Boot 2.7.4
・Quartz
・Mysql 5.7.39

在项目中集成Quartz

编辑build.gradle文件,添加JPA、JDBC Driver和Quartz的依赖关系。

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-quartz'
	runtimeOnly 'mysql:mysql-connector-java'
}

2. 设置Spring Boot应用程序的参数.

增加端点的接收端口和与Mysql的连接设置。
通过将spring.quartz.jdbc.initialize-schema设置为always,可以自动创建Quartz所需的表格。
但是由于每次启动都会进行初始化,如果不需要的话,请将其更改为never。
此外,MySQL用户需要关联适当的角色以创建表格。

server.port=8080
spring.datasource.platform=org.hibernate.dialect.MySQL5Dialect
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://***.***.***.***:33060/データベース名
spring.datasource.username=ユーザ名
spring.datasource.password=パスワード
spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true


#QUARTZ CONFIGS
spring.quartz.job-store-type=jdbc
spring.quartz.jdbc.initialize-schema=always

3. Quartz的启动和注册到DI容器中

Spring Boot启动时,同时启动Quartz并将其实例注册到DI容器中。

@SpringBootApplication
public class SchedulerApplication {

	public static void main(String[] args) {
		SpringApplication.run(SchedulerApplication.class, args);
	}

	@Bean
	public Scheduler scheduler(SchedulerFactoryBean factory) throws SchedulerException {
		Scheduler scheduler = factory.getScheduler();
		scheduler.start();
		return scheduler;
	}
}

4. 创建参数类

创建一个参数类作为作业参数的传递参数。
为了能够进行序列化,需要实现Serializable接口。

public class JobParameter implements Serializable {
    private static final long serialVersionUID = 1L;
    private final String uid;
    private final String name;
}

创建职业类别

这是一个将作为参数接收到的姓名输出到标准输出的作业。

public class SimpleJob implements Job {
    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap parameter = context.getJobDetail().getJobDataMap();
        JobParameter jobParameter = (JobParameter)parameter.get("parameter");
        System.out.println(MessageFormat.format("JobName: {0}",jobParameter.getName()));
    }
}

6. 创建终端点

這是一個擁有註冊和刪除端點的控制器類。

@RestController
@RequestMapping("/")
public class SimpleController {

    private final Scheduler scheduler;

    @Autowired
    public SimpleController(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    @GetMapping("/create")
    public ResponseEntity create() throws Exception {
        // パラメータ作成
        JobParameter jobParameter = new JobParameter("0001", "shigemax");

        // ジョブ生成及びパラメータ付与
        JobDetail job = JobBuilder.newJob(SimpleJob.class)
                .withIdentity("sample_job").build();
        job.getJobDataMap().put("parameter", jobParameter);

        // トリガー設定(120秒後に発火)
        Date afterFiveSeconds = Date.from(LocalDateTime.now().plusSeconds(120)
                .atZone(ZoneId.systemDefault()).toInstant());
        Trigger trigger = TriggerBuilder.newTrigger()
                .startAt(afterFiveSeconds)
                .build();

        // ジョブ登録
        this.scheduler.scheduleJob(job, trigger);

        return ResponseEntity.ok().build();
    }

    @GetMapping("/delete")
    public ResponseEntity delete() throws Exception {
        // ジョブ名で削除
        this.scheduler.deleteJob(new JobKey("sample_job"));
        return ResponseEntity.ok().build();
    }
}

7. Spring Boot启动

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.4)

8. 检查Quartz使用的表格。

mysql> SHOW TABLES;
+--------------------------+
| Tables_in_quartz         |
+--------------------------+
| QRTZ_BLOB_TRIGGERS       |
| QRTZ_CALENDARS           |
| QRTZ_CRON_TRIGGERS       |
| QRTZ_FIRED_TRIGGERS      |
| QRTZ_JOB_DETAILS         |
| QRTZ_LOCKS               |
| QRTZ_PAUSED_TRIGGER_GRPS |
| QRTZ_SCHEDULER_STATE     |
| QRTZ_SIMPLE_TRIGGERS     |
| QRTZ_SIMPROP_TRIGGERS    |
| QRTZ_TRIGGERS            |
+--------------------------+

9. 工作的注册 de

通过HTTP GET请求向http://localhost:8080/create发送请求。
120秒后,在标准输出上显示通过参数传递的名称。
JobClass: class com.example.scheduler.job.SimpleJob
JobName: shigemax

通过HTTP GET请求,请求发送至http://localhost:8080/create。
在120秒后,通过参数传递的名称将在标准输出中显示。
JobClass: class com.example.scheduler.job.SimpleJob
JobName: shigemax

10. 在MySQL容器中使用bash登录

在发送HTTP GET请求到http://localhost:8080/create后,
再通过HTTP GET请求到http://localhost:8080/delete。
确认作业已经删除,即使经过120秒,作业也不会被执行。

只需要一个选项,对以下内容进行原生的中文改写:

参考意见

 

bannerAds