Quartz.Net IJobFactory Interface
The Quartz.Net scheduler implements the factory method pattern to create the jobs that will be executed. Job factories are responsible for producing job instances. When you download the Quartz.Net distribution you get 2 different job factories. Today we will look at the IJobFactory interface in detail. In a later post we’ll look at the job factories that are included in the Quartz.Net distribution.
IJobFactory Interface
All job factories in Quartz.Net must implement the IJobFactory interface. Here is what the source code documentation has to say about the interface:
A JobFactory is responsible for producing instances of IJob classes.
this interface may be of use to those wishing to have their application produce IJob instances via some special mechanism, such as to give the opportunity for dependency injection.
The interface itself is quite simple, as it only has one method that needs to be implemented. Here is the interface definition:
public interface IJobFactory { IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler); }
The documentation for the NewJob method states:
Called by the scheduler at the time of the trigger firing, in order to produce a IJob instance on which to call Execute.
It should be extremely rare for this method to throw an exception - basically only the the case where there is no way at all to instantiate and prepare the Job for execution. When the exception is thrown, the Scheduler will move all triggers associated with the Job into the TriggerState.Error state, which will require human intervention (e.g. an application restart after fixing whatever configuration problem led to the issue with instantiating the Job.
The NewJob method will throw a SchedulerException if it was unable to create a new instance of the job. The method accepts 2 parameters. Let’s see what they’re used for now.
TriggerFiredBundle
The TriggerFiredBundle contains the the job detail, from which we can determine the job’s type and then use it to create a new instance of that type.
Scheduler
This is a reference to the scheduler itself, so you will have access to all of the functions this object supports, including the job context.
Creating a Job Factory
If you want to create a job factory, you will need to (at a minimum) implement the interface, grab the job detail from the bundle and get the job type. Once you have the type, create a new instance of that type. Then, initialize the object properly and return the initialized object.
In the next post I’ll describe the 2 job factories that are included in Quartz.Net and after that I will post a detail implementation of a job factory.