Search code examples
javaquartz-scheduler

How to create new JobDetail job in the run time?


I am configuring Quartz for client (NOT server) . If i need to create a new JobDetail job I would do the following

JobDetail job = JobBuilder.newJob(TestJob.class)
        .withIdentity("dummyJobName", "group1").build();

        Trigger trigger = . .  

        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger); 

Initially I thought I would feed an object of a class to newJob.

But the newJob method takes a class as an argument (not an instance of a class). JobBuilder org.quartz.JobBuilder.newJob(Class<? extends Job> jobClass)

I can't create a new class in the run time . This is not efficient at least .

So how can I add new JobDetail job in the run time ?


Should the TestJob class be abstract so that i could customize it in the run time . I'm very confused here

There was a similar question on stackoverflow. So it appears " the Quartz scheduler's JobFactory API to load job classes through a custom class-loader and that would allow you to add jobs truly dynamically "

But how ?


Solution

  • You cannot directly create JobDetail out of an object unless you serialize it (which is not recommended). What you can do is you can create a HashMap and add all your data into it and do the following.

    Map<String, Serializable> jobData = Maps.newHashMap();
            jobData.put("yourkey", "youdata");
            ...
    JobDetail job = newJob(TestJob.class).usingJobData(jobData)
          .build();
            //build your trigger
    scheduler.scheduleJob(job, trigger)