I am using Quartz.Net within a Windows Service to handle the scheduling of various jobs that I will be running. These jobs live inside of a database and each job is handled by a factory method inside of a separate class library.
I want to prevent the scheduler from running more than 1 of my jobs at a single time, however I can't use the [DisallowConcurrentExecution] attribute because I only have a single IJob in the scheduler - my factory method in a separate library handles the decision of what job to run.
Below is my single IJob:
public void Execute(IJobExecutionContext context)
{
JobDataMap dataMap = context.JobDetail.JobDataMap;
int jobId = dataMap.GetInt("JobId");
logger.InfoFormat("Job {0} has been triggered.", jobId);
//Create a new Job Instance
JobInstance jobInstance = new JobInstance()
{
CreateDate = DateTime.UtcNow,
ExecutionState = ExecutionState.Running,
CreateSource = "Agent Scheduler Service",
Job = new Job() { Id = jobId }
};
middlewareRepository.CreateJobInstance(jobInstance);
var job = jobFactory.GetJobImplementation(jobInstance);
//execute the job
job.Execute();
logger.InfoFormat("Job {0} has been executed.", jobId);
}
In this, there is a jobId which is my key for my job that I want to only allow a single instance to run at any given time.
This is how I load the jobs:
protected void LoadJobs()
{
logger.Info("Loading jobs.");
var jobs = middlewareRepository.GeActiveJobs();
foreach (var job in jobs)
{
IJobDetail jobDetail = JobBuilder.Create<JobDespatcher>()
.WithIdentity(job.Description)
.UsingJobData("JobId", job.Id)
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithCronSchedule(job.CronExpression)
.Build();
scheduler.ScheduleJob(jobDetail, trigger);
logger.InfoFormat("Job with id {0} ({1}) has been scheduled.", job.Id, job.Description);
}
}
Is there a way within Quartz.net to prevent the same job from running twice based on a key or a piece of data?