Quartz定时器---JobDataMap的运用

时间:2021-05-07 00:10:15

那么应该如何给一个任务提供属性或者配置呢?如何在任务的不同执行过程中保存或跟踪任务的状态呢?这是通过JobDetail的JobDataMap来实现。

JobDataMap
JobDataMap可以用来保存任何需要传递给任务实例的对象(这些对象要求是可序列化的),JobDataMap是java的Map接口的实现,添加了一些便利方法,下面的代码片断描述了如何使用JobDataMap保存数据:

Java代码

 

package mypackage;

import java.sql.Date;

import org.apache.log4j.BasicConfigurator;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;


 public static void main(String[] args) throws Exception{


      BasicConfigurator.configure();


     SchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();
       
        JobDetail jobDetail= new JobDetail("SayHelloWorldJob",
                Scheduler.DEFAULT_GROUP,
                SendMailJob.class);
 
         jobDetail.getJobDataMap().put("jobSays", "Hello World!");       
         jobDetail.getJobDataMap().put("myFloatValue", 3.141f);       
         jobDetail.getJobDataMap().put("myStateData", new ArrayList());    
         jobDetail.getJobDataMap().put("jobSays", "Hello World!");   
         jobDetail.getJobDataMap().put("myFloatValue", 3.141f);   
         jobDetail.getJobDataMap().put("myStateData", new ArrayList()); 


        
        Trigger trigger= new SimpleTrigger("SayHelloWorldJobTrigger",
                Scheduler.DEFAULT_GROUP,
                new  Date(System.currentTimeMillis() +2* 1000),
                null,
                1,
                1000L);
        
        scheduler.scheduleJob(jobDetail, trigger);

        scheduler.start();
       
       
    }
下面的示例描述了如何在任务执行过程中从JobDataMap获取数据:

Java代码
public class DumbJob implements Job {              
       public DumbJob() {       
       }              
      
       public void execute(JobExecutionContext context)       
           throws JobExecutionException       
       {       
           String instName = context.getJobDetail().getName();       
           String instGroup = context.getJobDetail().getGroup();                  
           JobDataMap dataMap = context.getJobDetail().getJobDataMap();                  
           String jobSays = dataMap.getString("jobSays");       
           float myFloatValue = dataMap.getFloat("myFloatValue");       
           ArrayList state = (ArrayList)dataMap.get("myStateData");       
           state.add(new Date());                  
           System.err.println("Instance " + instName + " of DumbJob says: " + jobSays);       
       }       
   }