Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a reference to an instantiated object within a Quartz.Net job?

Tags:

quartz.net

I have a windows service with embedded Quartz.Net but can't seem to find a way to create a reference to an instantiated object within a Quartz.Net job...

When the windows service is started it instantiates some objects for logging, database access and other purposes so I'd like my Quartz.Net jobs to use these already instantiated objects instead of creating its own instances of these objects. However, Quartz.Net jobs are instantiated by the scheduler using the no-argument constructor and hence there is no way to pass a reference using the constructor.

Do I have to create my own implementation of the JobFactory and is that the only way to achieve this?

like image 533
Dean Kuga Avatar asked Jan 03 '11 17:01

Dean Kuga


3 Answers

I think the approach that works for this situation is to use a job listener. You can create a "dummy" job which does nothing, and a listener which detects when the job has been run. You can instantiate the listener with references to any dependencies, as long as they are available at the time you set up the job scheduling.

IJobDetail job = JobBuilder.Create<DummyJob>()
            .WithIdentity("job1") 
            .Build();

        ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("trigger1")
            .StartNow()
            .WithSimpleSchedule(x => x
                .WithInterval(interval)
                .RepeatForever())
            .Build();

        _scheduler.ScheduleJob(job, trigger);

       MyJobListener myJobListener = new MyJobListener (dependency1, dependency2);

        _scheduler.ListenerManager.AddJobListener(myJobListener, KeyMatcher<JobKey>.KeyEquals(new JobKey("job1")));
like image 168
Jonny Cundall Avatar answered Sep 26 '22 15:09

Jonny Cundall


You can add key-value pairs of objects in jobDetail.JobDataMap and retrieve them from(JobExecutionContext) context.JobDetail.JobDataMap.

like image 29
roman Avatar answered Sep 23 '22 15:09

roman


Different context (Linux/JAVA), but create your own Factory that inherits from the Quartz one. Override the method "createScheduler". Call the super method, save instance in a static (synchronized) hash map. Write static method to get instance by name.

like image 42
bob Avatar answered Sep 26 '22 15:09

bob