0

How can I access my OSGi services in a quartz trigger?

Below, my service companyDao is null when the timer is triggered. Do I need to give the bundle context to the scheduler or the job? if so, how?

@Service
@Component(immediate = true, specVersion = "1.1", inherit = true)
public class TechnicalStageTimer implements Job {

    @Reference(cardinality = MANDATORY_UNARY, policy = DYNAMIC)
    protected CompanyDao companyDao;

    private static final Logger LOG = LoggerFactory.getLogger(TechnicalStageTimer.class.getCanonicalName());

    Scheduler scheduler;

    @Activate
    public void start(BundleContext context) throws Exception {

        LOG.warn("Starting Timer TechnicalStageTimer");
        SchedulerFactory sf = new StdSchedulerFactory();
        scheduler = sf.getScheduler();

        JobDetail job = JobBuilder.newJob(TechnicalStageTimer.class).build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(11, 00)) // every day at 11:00
                .build();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();

    }

    @Deactivate
    public void stop(BundleContext context) throws Exception {
        scheduler.shutdown(true);
    }

    public void execute(JobExecutionContext context)
            throws JobExecutionException {

        LOG.warn("Timer Triggered");
        List<Company> companies = companyDao.getPool();
    }

}
user2641043
  • 405
  • 3
  • 12

1 Answers1

0

You must remember one thing - Quartz instantiate new job instance for every execution. If you want to have access to external components (from new job point of view) you have to bring it somehow. In such case you have two options:

  • job execution context
  • static field reference

First one is much more reliable, second is rather hack.

splatch
  • 1,547
  • 2
  • 10
  • 15