Running a Quartz job with Java class name stored i

2019-06-14 11:52发布

I have a two jobs in Quartz which will run perfetly well but I find I have to use code like:

jd = new JobDetail(sj.getJobName(), scheduler.DEFAULT_GROUP, PollJob.class);
ct = new CronTrigger(sj.getJobTrigger(), scheduler.DEFAULT_GROUP, "0 20 * * * ?");
        scheduler.scheduleJob(jd, ct);

I have to hardcode PollJob.class to run the job and sj is an object read from the database containing PollJob's details. But I would like to set PollJob.class from the database as well. I've tried casting to a class by:

Class cls = Class.forName(sj.getJobJavaClassFile());
jd = new JobDetail(sj.getJobName(), scheduler.DEFAULT_GROUP, cls));

And using a class reference directly as:

    jd = new JobDetail(sj.getJobName(), scheduler.DEFAULT_GROUP, Class.forName sj.getJobJavaClassFile()));

But the job simply doesn't execute. There are no exceptions generated that I can see and no stack trace?

I'm running a JVM on Windows 7.

Any ideas?

Mr Morgan.

1条回答
小情绪 Triste *
2楼-- · 2019-06-14 12:26

I'm guessing that you have stored the class in your database as a String, and you are trying to turn that into a class? I had the same problem.

The details of the job I need to create are provided in a BatchJobDto object. It contains things like the name of the job, the name of the class as a String and so on. In particular batchJobDto.getClassName() return a String which is the fully-qualified name of my job class ("com.foo.bar.MyJob" or whatever). I create the trigger, get the class from the String and create the job. The sequence for getting the class from the String is:

Class<? extends Job> jobClass = null;
try {
    jobClass = (Class<? extends Job>)
                  Class.forName(batchJobDto.getClassName());
} catch(ClassNotFoundException e) {
    logger.error("createJob(): ClassNotFoundException on job class {} - {}",
        batchJobDto.getClassName(), e.getMessage());
} catch(Exception e) {
    logger.error("createJob(): Exception on job class {} - {}",
        batchJobDto.getClassName(), e.getMessage());
}

The logging is done with slf4j, which allows you to use a parameterised message ("{}" as above).

There's an unchecked cast in there, but if your classname string describes a class which is a Quartz job (implements Job) then I believe it should always work.

查看更多
登录 后发表回答