🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. 什么是持久化** ```java @Slf4j public class UserJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); //获取从 JobDetail 中传递的 count,然后 +1 再存入 JobDetail jobDataMap.put("count", jobDataMap.getInt("count") + 1); log.info("count: {}", jobDataMap.getInt("count")); } } ``` 当被触发器触发时日志打印如下: ``` //可以看到,被同一个触发器触发的任务, //下一次任务记不住上一次任务传递的数据,这就是非持久化 2023-03-31T22:39:51 ...job.UserJob : count: 1 2023-03-31T22:39:55 ...job.UserJob : count: 1 2023-03-31T22:39:59 ...job.UserJob : count: 1 2023-03-31T22:40:03 ...job.UserJob : count: 1 2023-03-31T22:40:07 ...job.UserJob : count: 1 ``` <br/> **2. 开启持久化** 如果要开启持久化只需要标注注解`@PersistJobDataAfterExecution`即可。 ```java @Slf4j @PersistJobDataAfterExecution public class UserJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); jobDataMap.put("count", jobDataMap.getInt("count") + 1); log.info("count: {}", jobDataMap.getInt("count")); } } ``` 当被触发器触发时日志打印如下: ``` //可以看到,被同一个触发器触发的任务, //下一次任务可以记住上一次任务传递的数据,这便是持久化的功能之一 2023-03-31T22:46:02 ...job.UserJob : count: 1 2023-03-31T22:46:06 ...job.UserJob : count: 2 2023-03-31T22:46:10 ...job.UserJob : count: 3 2023-03-31T22:46:14 ...job.UserJob : count: 4 2023-03-31T22:46:18 ...job.UserJob : count: 5 ``` >[info]持久化只对 JobDetail 中的 JobDataMap 有效,如果是触发器的 JobDataMap 则是无效的。 ```java public class AccountJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { //JobDetail 中的 JobDataMap JobDataMap fromJobData = context.getJobDetail().getJobDataMap(); //触发器中的 JobDataMap JobDataMap fromTriggerData = context.getTrigger().getJobDataMap(); } } ```