Home  >  Article  >  Java  >  How to integrate Quartz with SpringBoot

How to integrate Quartz with SpringBoot

PHPz
PHPzforward
2023-05-10 18:46:06902browse

Basic dependencies

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

Quartz is a scheduled task framework that is commonly used in single application projects. The scheduled tasks can be mainly divided into:

  • Tasks in memory : Generally defined and stored inside the project, if the project is restarted, if the task is not automatically executed , it will not be turned on again.

  • Persistent tasks: Store the characteristics of the task in the database. After the project is restarted, the originally executing task can be re-read and continued execution.

cron expression

corn is used to control the time when the task is triggered.

I list some commonly used ones:

  • Trigger every second

"* * * * * *":
  • Every 5 Execute once per second

*/5 * * * * ?
  • Trigger every minute

"0 * * * * ?"
  • Trigger every hour

"0 * * * * ?"
  • Trigger once every day at 10 o'clock

"0 0 10 * * ?"
  • Trigger once every day at 0 o'clock

"0 0 0 * * ?"

General

You need to add the @EnableScheduling annotation to the startup class.

Memory tasks

Tasks that are executed when the project starts

Directly define an execution task, for example:

Output every secondTest

@Service
public class ScheduleTest {

    @Scheduled(cron = "0/1 * * * * *")
    public void test() {
        System.out.println("测试");
    }
}

Startup class:

@SpringBootApplication
@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

After startup, the corresponding content will be output in the console.

Manually control a task

Here we need to define the task ourselves.

Define Task

By implementing the Job interface, a task can be defined, and we can manually control the opening of this task.

public class SimpleJob implements Job {
    @Override
    public void execute(JobExecutionContext context) {
        System.out.println("自定义任务");
    }
}

Use Web-Controller to start this task

Import dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.3.6.RELEASE</version>
</dependency>

Writing Controller, this is a fixed way of writing.

  • Specify the task: JobBuilder.newJob(task.class) .withIdentity(task name, task group).build();

  • Specify cron expression and create Trigger:

    • ##CronScheduleBuilder.cronSchedule(cron expression);

    • TriggerBuilder.newTrigger().withIdentity(initiator name, starter group) .withSchedule(cron).build();

  • Calling task:

    scheduler.scheduleJob (task type object, launcher object)

  • /**
     * @ClassName
     * @Description
     * @Author:chengyunlai
     * @Date
     * @Version 1.0
     **/
    @RestController
    public class DynamicScheduleController {
    
        @Autowired
        private Scheduler scheduler;
    
        @GetMapping("/addSchedule")
        public String addSchedule() throws SchedulerException {
            int random = ThreadLocalRandom.current().nextInt(1000);
            // 1. 创建JobDetail,指定定时任务实现类的类型
            JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class)
                    .withIdentity("test-schedule" + random, "test-group").build();
            // 2. 创建Trigger,并指定每3秒执行一次
            CronScheduleBuilder cron = CronScheduleBuilder.cronSchedule("0/3 * * * * ?");
    
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("test-trigger" + random, "test-trigger-group")
                    .withSchedule(cron).build();
    
            // 3. 调度任务
            scheduler.scheduleJob(jobDetail, trigger);
            return "success";
        }
Enter the address of the project through the browser, the default is

localhost:8080/addSchedule, after entering it, you can see that the console outputs the output content of the task execution.

Persistence

If the project is restarted, the above

SimpleJob scheduled task will not be restarted. The solution is to persist the task. Quartz provides a solution, and SpringBoot simplifies this operation. We only need to configure: database, data source, and JDBC to operate the database.

Dependencies:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.8</version>
</dependency>

  • Use mysql database: import its driver, mysql-connector-java.

  • Using Druid as our data source: druid.

  • Using spring-jdbc helps us automatically store task information into the database.

Configuration

# 设置将定时任务的信息保存到数据库
spring.quartz.job-store-type=jdbc

# 每次应用启动的时候都初始化数据库表结构
# 如果 spring.quartz.jdbc.initialize-schema 设置为 always 的话有个问题:每次重启应用的时候,跟 Quartz 相关的表会被删除重建!
# 所以为了避免表被重复创建,我们可以提前创建表,然后将其指定为never
spring.quartz.jdbc.initialize-schema=never

# 数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/scheduled?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root

Quartz has prepared a sql data table for us

Official website: Downloads (quartz-scheduler.org)

Take me: quartz-2.3.0-SNAPSHOT as an example:

After downloading the source code, find the directory

jdbcjobstore:

quartz-2.3.0-SNAPSHOT \src\org\quartz\impl\jdbcjobstore

Then there will be a series of

sql files. Just find the sql file that matches your database. I use mysql .

How to integrate Quartz with SpringBoot

Execute the SQL file to create the table. My database name is:

scheduled. You should be able to see it from my URL.

After the table creation is completed, all configuration work is over, start the program, re-enter in the browser:

localhost:8080/addSchedule, then refresh the database, you will find that the task is persisted After restarting the project, the task will still be executed automatically.

Pause tasks and delete tasks

When we manually start the task, we will specify:

  • The name and group of the task

  • JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class) .withIdentity(任务名,任务组).build();
When pausing and resuming a task, you need to use

JobKey.jobKey (task name, task group) to get a JobKey, and then use scheduler.pauseJob(jobkey) can pause the task; scheduler.resumeJob(jobKey)resume the task.

  • When deleting a task, we need to delete both the task and the trigger. Above we can get this

    jobkey to represent the task. We also need to get the trigger. Similarly We also defined the launcher's name and group.

  • `TriggerBuilder.newTrigger().withIdentity(启动器的名字, 启动器的分组) .withSchedule(cron).build();`

TriggerKey.triggerKey((name of launcher, group of launcher);You can also get trigger to represent the launcher.

  • 通过以下顺序完整删除任务

    • scheduler.deleteJob(jobKey);

    • scheduler.unscheduleJob(triggerKey);

    • scheduler.pauseTrigger(triggerKey);

    • // 停止触发器

    • // 移除触发器

    • // 删除任务

// 暂停
@GetMapping("/pauseSchedule")
public String pauseSchedule(String jobName, String jobGroup) throws SchedulerException {
    JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
    // 获取定时任务
    JobDetail jobDetail = scheduler.getJobDetail(jobKey);
    if (jobDetail == null) {
        return "error";
    }
    scheduler.pauseJob(jobKey);
    return "success";
}

// 恢复
@GetMapping("/remuseSchedule")
public String remuseSchedule(String jobName, String jobGroup) throws SchedulerException {
    JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
    // 获取定时任务
    JobDetail jobDetail = scheduler.getJobDetail(jobKey);
    if (jobDetail == null) {
        return "error";
    }
    scheduler.resumeJob(jobKey);
    return "success";
}

// 删除定时任务
@GetMapping("/removeSchedule")
public String removeSchedule(String jobName, String jobGroup, String triggerName, String triggerGroup) throws SchedulerException {
    TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroup);
    JobKey jobKey = JobKey.jobKey(jobName, jobGroup);

    Trigger trigger = scheduler.getTrigger(triggerKey);
    if (trigger == null) {
        return "error";
    }
    // 停止触发器
    scheduler.pauseTrigger(triggerKey);
    // 移除触发器
    scheduler.unscheduleJob(triggerKey);
    // 删除任务
    scheduler.deleteJob(jobKey);
    return "success";
}

The above is the detailed content of How to integrate Quartz with SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete