參考下列片段:
// define the job and tie it to our HelloJob class JobDetail job = newJob(HelloJob.class) .withIdentity("myJob", "group1") // name "myJob", group "group1" .build(); // Trigger the job to run now, and then every 40 seconds Trigger trigger = newTrigger() .withIdentity("myTrigger", "group1") .startNow() .withSchedule(simpleSchedule() .withIntervalInSeconds(40) .repeatForever()) .build(); // Tell quartz to schedule the job using our trigger sched.scheduleJob(job, trigger);
line 1~3說明了最簡單建立Job的方式,提供簡單的extend Job的Class!Job的建立生命週期如下:
- Shedule建立執行Job之前(call job's execute(..)),便為Job建立新的instance(如上述的HelloJob)
- Shedule call job's execute(..)
- job使用完畢,等待被GC回收
那麼,我們要怎麼樣在Job被execute之前指定特定資料呢?
使用JobDataMap
// define the job and tie it to our DumbJob class JobDetail job = newJob(DumbJob.class) .withIdentity("myJob", "group1") // name "myJob", group "group1" .usingJobData("jobSays", "Hello World!") .usingJobData("myFloatValue", 3.141f) .build();
2.取得資料:
public class DumbJob implements Job { public DumbJob() { } public void execute(JobExecutionContext context) throws JobExecutionException { JobKey key = context.getJobDetail().getKey(); JobDataMap dataMap = context.getJobDetail().getJobDataMap(); String jobSays = dataMap.getString("jobSays"); float myFloatValue = dataMap.getFloat("myFloatValue"); System.err.println("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue); } }
如上述範例,可先於創立JobDetail時指定資料,後於Job execute()時使用getJobDetail().getJobDataMap();取得所需資料。
然而需注意的是,置放於DataMap()的資料皆需為serialized
參考:Lesson 3: More About Jobs and Job Details
沒有留言:
張貼留言