Search code examples
javaquartz-schedulerquartz

Can I define job instance using method instead of class Quartz?


I'm reading Quartz documentation and trying to understand can I pass inside Job instance method instead of class.

For example, in case with class I need to write:

public class MyJobClass implements Job {

    public MyJobClass() {
        // Instances of Job must have a public no-argument constructor.
    }

    public void execute(JobExecutionContext context)
            throws JobExecutionException {

        JobDataMap data = context.getMergedJobDataMap();
        System.out.println("someProp = " + data.getString("someProp"));
    }    
}

And defining a Job Instance like:

JobDetail job1 = newJob(MyJobClass.class) // what about method here
    .withIdentity("job1", "group1")
    .usingJobData("someProp", "someValue")
    .build();

By the same principle, I tried to define job instance passing method like:

// define the job
JobDetail job = newJob(testMethod())
               .withIdentity("job1", "group1")
               .build();

And method looks like:

private Class<? extends Job> testMethod() {
    //...  
    return null;
}

But I get the error:

java.lang.IllegalArgumentException: Job class cannot be null.

Updated: I return null in method, because if I don't do this I get: enter image description here


Solution

  • Your testMethod() method returns null. Quartz does not accept null and fails.

    Quartz wants to manage jobs by itself so it is why you are only allowed to pass class not instance.

    Why do you need to provide your own instance? If you want to make it "persistent" to keep state between executions then Quartz provides stateful job concept, see http://www.quartz-scheduler.org/api/2.3.0/org/quartz/StatefulJob.html