1

I am working on writing a Job when my application is deployed. This Job should run every 5 mins and it should start immediately. But the problem is it is starting 5 mins after the deployment and repeating for every five minutes. Please help me with the changes required to start it immediately when the application is deployed.

 public void contextInitialized(ServletContextEvent servletContextEvent) {
        logger.info("contextInitialized() ,Starting instantiating Processor Engine");
        try{
        JobDetail job = newJob(MyServiceProcessor.class).withIdentity(
                "CronQuartzJob", "Group").build();
        Trigger trigger = newTrigger().withIdentity("TriggerName", "Group").withSchedule(CronScheduleBuilder.cronSchedule("0 0/5 * * * ?")).build();
        scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger);

        }
        catch (SchedulerException e) {
            logger.error(", contextInitialized() ,Problem in starting Processor Engine"+e);
    }
  • which server and framework you are using for web application?? – Poornima Jan 12 '17 at 06:31
  • Hi! If one of the answers below helped you solve your problem, please remember to mark it as accepted, so your question appears as answered, thanks :) – walen Jan 24 '17 at 09:34

2 Answers2

0

I think in that way you can't start the job immediately. The cron-expression triggers each 0 or 5 minutes.

Alternative you could instantiate the job additionally and execute it manually in the contextInitialized(), if you dont need the JobExecutionContext.

MyServiceProcessor mjob = new MyServiceProcessor();
mjob.execute(null);
milchreis
  • 79
  • 7
  • `"The cron-expression triggers each 0 or 5 minutes"` That's not how cron syntax works. `0/5` means "every five minutes starting at minute zero". Besides, directly calling `execute()` means you're overriding the Scheduler: no overlapping control, no interrupting, no trace of the job if you call `getCurrentlyExecutingJobs()`, no info about last execution or elapsed time... – walen Jan 13 '17 at 10:55
0

Don't use CronTrigger for such simple scheduling. Use SimpleTrigger instead:

Trigger trigger = newTrigger()
        .withIdentity("TriggerName", "Group")
        .withSchedule(SimpleTriggerBuilder.simpleSchedule()
                    .withIntervalInMinutes(5)
                    .repeatForever())
        .build();

This will schedule your job to fire right now, and then every 5 minutes.

For more uses of SimpleTrigger you can read Quartz's tutorial on it.

walen
  • 7,103
  • 2
  • 37
  • 58