Running a Quartz job with Java class name stored in database

醉酒当歌 提交于 2019-12-23 04:33:13

问题


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:


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.



来源:https://stackoverflow.com/questions/3185221/running-a-quartz-job-with-java-class-name-stored-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!