Search code examples
javaquartz-scheduler

Run Quartz job synchronous


I have a situation that I don't know how should I handle it.

I have a job in quartz which should start another nested job and get some results of the nested job and process them.

As I know, quartz run its job asynchronously. So, the thread which start the nested job cannot wait until the result of nested job being passed.

What is the solution here?


Solution

  • First of all quartz has a thread pool for running its jobs. You can read about it here:

    In addition keep in mind that quartz can run jobs even in distributed manner. It allows to be run in cluster of 'active-active' servers, in this case you can't do any assumption on which of servers the job can be triggered. So implementing a singleton as jbh has stated can be tricky (at least you have been warned now :) )

    In general, I think quartz should do what its good for - to run jobs. I don't think that implementing any complicated logic on top of this is a good idea. From your question I understand that you're trying to run one job from another (say job A runs job B). This makes sense if you have different trigger(s) assigned to A and B (otherwise why should B implemented as a quartz job?). So maybe you can refactor your code of job B so that the logic executed in B will be implemented in some class which is not related to quartz(say class C)? In this case you could assign different triggers to jobs A and B but inside just execute the code in class C?

    Example (your approach):

    class A implements Job {
      public void execute(JobExecutionContext context) throws JobExecutionException {
          // do A's stuff
          // call Job B somehow (???)
      }
    }
    
    
    class B implements Job {
      public void execute(JobExecutionContext context) throws JobExecutionException {
          // do something
      }
    

    }

    My suggestion:

    class C {
       doSomeLogic(...) {...}
    }
    
    
    class A implements Job {
             public void execute(JobExecutionContext context) throws   JobExecutionException {
            // do A's stuff
            C c = new C();
            c.execute();  
      }
    
    
    class B implements Job {
             public void execute(JobExecutionContext context) throws JobExecutionException {            
            C c = new C();
            c.execute();  
      }
    

    }

    Hope this helps.