企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 1. 任务全局唯一 每个 JobDetail 都有一个唯一的身份,在全局中该 JobDetail 始终只能存在一个。 ```java JobDetail jobDetail = JobBuilder .newJob(AccountJob.class) //任务ID .withIdentity("job1", "job-group1") .build(); ``` 上面已经创建了 ID 为`job-group1.job1`的任务,如果再重新创建则抛出如下异常,阻止你再重新创建相同的任务。 ``` Unable to store Job : 'job-group1.job1', because one already exists with this identification. org.quartz.ObjectAlreadyExistsException: Unable to store Job : 'job-group1.job1', because one already exists with this identification. at org.quartz.simpl.RAMJobStore.storeJob(RAMJobStore.java:279) ``` >[info]触发器虽然也有`withIdentity(name, group)`来设置该触发器的 ID。但如果重复创建,则后创建的触发器会覆盖前面创建的触发器,不会触发异常。 <br/> # 2. 触发器与任务的数量绑定关系 * 一个触发器(Trigger)只能与一个任务(JobDetail)绑定。 * 一个任务(JobDetail)可以与多个触发器(Trigger)绑定。 下面演示一个任务如何与多个触发器绑定。 **1. 定时任务要执行的业务代码** ```java @Slf4j public class UserJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { TriggerKey triggerKey = context.getTrigger().getKey(); JobKey jobKey = context.getJobDetail().getKey(); log.info("触发器ID: {}", triggerKey.getGroup() + "." + triggerKey.getName()); log.info("任务ID: {}\n", jobKey.getGroup() + "." + jobKey.getName()); } } ``` <br/> **2. 一个任务绑定多个触发器** ```java public void jobManyTrigger() throws SchedulerException { JobDetail jobDetail = JobBuilder.newJob(UserJob.class) .withIdentity("job4", "job-group1") .build(); Trigger trigger1 = TriggerBuilder.newTrigger() .withIdentity("trigger3", "trigger-group1") .startNow() .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(4) .repeatForever() ) .build(); Trigger trigger2 = TriggerBuilder.newTrigger() .withIdentity("trigger4", "trigger-group1") //除了第一个触发器,其余的触发器用 forJob 绑定 job .forJob(jobDetail) .startNow() .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(5) .repeatForever() ) .build(); Trigger trigger3 = TriggerBuilder.newTrigger() .withIdentity("trigger5", "trigger-group1") //除了第一个触发器,其余的触发器用 forJob 绑定 job .forJob(jobDetail) .startNow() .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(6) .repeatForever() ) .build(); //第一个触发器调用 scheduleJob(JobDetail, Trigger) 进行绑定任务 scheduler.scheduleJob(jobDetail, trigger1); //剩余的触发器调用 scheduleJob(Trigger) 进行绑定,不能再调用 scheduleJob(JobDetail, Trigger) scheduler.scheduleJob(trigger2); scheduler.scheduleJob(trigger3); scheduler.start(); } ``` 启动后日志打印如下: ``` //同一个任务可以由多个触发器触发 2023-03-31T18:07:05.36...job.UserJob : 触发器ID: trigger-group1.trigger3 2023-03-31T18:07:05.36...job.UserJob : 任务ID: job-group1.job4 ... 2023-03-31T18:07:07.36...job.UserJob : 触发器ID: trigger-group1.trigger4 2023-03-31T18:07:07.36...job.UserJob : 任务ID: job-group1.job4 ... 2023-03-31T18:07:09.36...job.UserJob : 触发器ID: trigger-group1.trigger5 2023-03-31T18:07:09.36...job.UserJob : 任务ID: job-group1.job4 ```