Home > Java > javaTutorial > body text

How to use Quartz to implement scheduled tasks in Java?

王林
Release: 2023-05-08 10:46:17
forward
1534 people have browsed it

Scheduler will create a new Job instance based on JobDetail every time it is executed, so as to avoid the problem of concurrent access (the instance of jobDetail is also new)

Quzrtz scheduled tasks are executed concurrently by default, no It will wait for the last task to be executed, and it will be executed as long as the interval is up. If the scheduled task is executed for too long, it will occupy resources for a long time and cause other tasks to be blocked.

@DisallowConcurrentExecution: On the job class, concurrent execution is prohibited Multiple instances of the same job definition (defined by JobDetail).

How to use Quartz to implement scheduled tasks in Java?

  • scheduler: It can be understood as a work container or workplace for scheduled tasks. All scheduled tasks are placed in it and can be opened and stop.

  • trigger: It can be understood as the work rule configuration of a scheduled task. For example, it is called every few minutes, or it is specified to be executed at that time point every day.

  • jobDetail: Scheduled task information, such as configuring the name of the scheduled task, group, etc.

  • job: The place where the real business processing logic of scheduled tasks is located.

Simple example

TestClient.Java

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class TaskClient {

    public static void main(String[] args) {
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job1", "group1")  //设置JOB的名字和组
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "trigger1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
                        .repeatForever())
                .build();
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException ex) {
            ex.printStackTrace();
        }

    }

}
Copy after login

TaskJob.Java

import cn.hutool.core.date.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class TaskJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("TaskJob => " + DateUtil.now());
    }
}
Copy after login

How to use Quartz to implement scheduled tasks in Java?

##usingJobData

Pass parameters to scheduled tasks through usingJobData

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class TaskClient {

    public static void main(String[] args) {
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job1", "group1")
                .usingJobData("job","jobDetail1.JobDataMap.Value")
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "trigger1")
                .usingJobData("trigger","trigger.JobDataMap.Value")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
                        .repeatForever())
                .build();
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException ex) {
            ex.printStackTrace();
        }

    }

}
Copy after login

TaskJob.java

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

public class TaskJob implements Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        JobDataMap triggerMap = context.getTrigger().getJobDataMap();
        JobDataMap mergeMap = context.getMergedJobDataMap();


        System.out.println("jobDataMap => " + jobDataMap.getString("job"));
        System.out.println("triggerMap => " + triggerMap.getString("trigger"));
        System.out.println("mergeMap => " + mergeMap.getString("trigger"));
    }
}
Copy after login

How to use Quartz to implement scheduled tasks in Java?

Assign values ​​through attributes

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class TaskClient {

    public static void main(String[] args) {
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job1", "group1")
                .usingJobData("job","jobDetail1.JobDataMap.Value")
                .usingJobData("name","jobDetail1.name.Value") //通过 setName 自动赋值
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "trigger1")
                .usingJobData("trigger","trigger.JobDataMap.Value")
                .usingJobData("name","trigger.name.Value")  //如果 Trigger 有值,会覆盖 JobDetail
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
                        .repeatForever())
                .build();
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException ex) {
            ex.printStackTrace();
        }

    }

}
Copy after login
import org.quartz.*;

public class TaskJob implements Job {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        System.out.println("name => " + name);
    }
}
Copy after login

Non-concurrent execution

@DisallowConcurrentExecution job class prohibits concurrent execution of multiple instances of the same job definition (JobDetail definition).

import cn.hutool.core.date.DateUtil;
import org.quartz.*;

@DisallowConcurrentExecution
public class TaskJob implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        System.out.println("Time => " + DateUtil.now());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

@PersistJobDataAfterExecution

Persistent JobDataMap in JobDetail (invalid for datamap in trigger), if a task is not

import cn.hutool.core.date.DateUtil;

import org.quartz.*;

//持久化JobDetail中的JobDataMap(对 trigger 中的 datamap 无效),如果一个任务不是
@PersistJobDataAfterExecution
public class TaskJob implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap triggerMap = context.getJobDetail().getJobDataMap();
        triggerMap.put("count", triggerMap.getInt("count") + 1);
        System.out.println("Time => " + DateUtil.now() + " count =>" + triggerMap.getInt("count"));

    }
}
Copy after login

Client

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class TaskClient {

    public static void main(String[] args) {
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job1", "group1")
                .usingJobData("job","jobDetail1.JobDataMap.Value")
                .usingJobData("name","jobDetail1.name.Value") //通过 setName 自动赋值
                .usingJobData("count",0) //通过 setName 自动赋值
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "trigger1")
                .usingJobData("trigger","trigger.JobDataMap.Value")
                .usingJobData("name","trigger.name.Value")  //如果 Trigger 有值,会覆盖 JobDetail
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
                        .repeatForever())
                .build();
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException ex) {
            ex.printStackTrace();
        }

    }

}
Copy after login

The above is the detailed content of How to use Quartz to implement scheduled tasks in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template