Search code examples
javascheduled-tasksquartz-schedulerjob-schedulingcrontrigger

Quartz CronTrigger firing itself many times


I'm trying to implement a CronTrigger using the quartz api, it works but not so good, when the cron expression it's reached, the job executes infinitely, and i don't know why.

I just want to execute it 1 time when the cron expression will reached.

Can someone helpme to know why its executing many times?

This is my code

    package cron;

import java.text.ParseException;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

import cron.HelloJob;

public class Quartz {

    public static void main(String[] args) throws ParseException, SchedulerException {
        JobDetail job = new JobDetail();
        job.setName("health check");
        job.setJobClass(HelloJob.class);

        System.out.println("After job");

        CronTrigger triggr = new CronTrigger();
        triggr.setName("Check");
        triggr.setCronExpression("* 50 07 * * ? *");

        System.out.println("Cron expression" + triggr.getCronExpression());

        Scheduler scheduler2 = new StdSchedulerFactory().getScheduler();
        scheduler2.start();
        scheduler2.scheduleJob(job, triggr);
    }

}

This is the job

package cron;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;


public class HelloJob implements Job {
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("Hello job");


    }


}

And this is my output Many prints

And I just want 1 print with my cron


Solution

  • You configured it to fire each second (first *):

    triggr.setCronExpression("* 50 07 * * ? *");
    

    To solve it, just put a value, 0 for instance:

    triggr.setCronExpression("0 15 15 * * * *");
    

    This should trigger at 15:15:00 (hh:mm:ss) every day.

    See usage here:

    http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html