第2篇讲述了怎样给job传递参数或者随机数,但是,这个随机数不会更新,举个例子,执行第一次job的时 随机数3 ,执行第2次job,随机数仍然是3,因为执行每一次job都会实例化job实例对象
JobDataMap更新的使用场景:
举个例子,执行第一次job的时随机数3 ,间隔5秒,执行第2次job,随机数仍然是3+5-8
使用@PersistJobDataAfterExecution可更新JobDataMap
JobDataMap更新示例
代码示例:
package com.gblfy;import com.gblfy.job.MyJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;import java.util.Random;public class QuartzStart {public static void main(String[] args) throws SchedulerException {//创建SchedulerScheduler scheduler = StdSchedulerFactory.getDefaultScheduler();scheduler.start();Random random = new Random();int count = random.nextInt(10);//创建JobDetailJobDetail jobDetail = JobBuilder.newJob(MyJob.class)//唯一标识.withIdentity("jobDetail1", "group1")//添加参数通过usingJobData方法,传递给job.usingJobData("count",count).build();//创建TriggerTrigger trigger = TriggerBuilder.newTrigger()//立即执行.startNow()//任务周期.withSchedule(SimpleScheduleBuilder.simpleSchedule()//间隔周期 单位s.withIntervalInSeconds(5)//一直执行.repeatForever()).build();//把jobDetail和trigger注册到scheduler中scheduler.scheduleJob(jobDetail, trigger);try {Thread.sleep(60000);} catch (InterruptedException e) {e.printStackTrace();}scheduler.shutdown();}
}
job
package com.gblfy.job;import lombok.Getter;
import lombok.Setter;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;import java.time.LocalTime;@PersistJobDataAfterExecution
public class MyJob implements Job {@Getter@Setterprivate int count;@Overridepublic void execute(JobExecutionContext context) throws JobExecutionException {LocalTime localTime = LocalTime.now();count++;context.getJobDetail().getJobDataMap().put("count",count);System.out.println(localTime.toString() + "----count的值=" + count);}
}