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).
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(); } } }
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()); } }
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(); } } }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")); } }
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(); } } }
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); } }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(); } } }@PersistJobDataAfterExecutionPersistent 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")); } }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(); } } }
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!

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor