Кварцевая функция scheduleJob не работает должным образом - PullRequest
0 голосов
/ 28 марта 2012

У меня есть некоторые запланированные функции в моем веб-приложении, которое работает на Glassfish. Функции планируется запускать каждый день, каждую неделю, каждый месяц и каждый год. Но запускается только ежедневная запланированная функция. Пожалуйста, посмотрите на код:

public class SchedulerServlet extends GenericServlet {

    private static Boolean isLoaded = Boolean.FALSE;

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    private void scheduleCronJob(String ejbName, String methodName, String cronExpr) {
        final String jobName = "quartz job: " + ejbName + "." + methodName;
        System.out.println("SchedulerServlet.scheduleCronJob: ejbName: "+ ejbName +" methodname: "+ methodName +" cronExpr: "+ cronExpr ); //asd
        CronTrigger cronTrigger = new CronTrigger(jobName, "Quartz Trigger");
        try {
            cronTrigger.setCronExpression(cronExpr);
            scheduleJob(ejbName, methodName, cronTrigger, "-cron");
        } catch (Exception ex) {
        System.out.println("STATE : " + "scheduleCronJob fonksiyonunda hata var.") ;
            Logger.getLogger(SchedulerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void scheduleSimpleJob(String ejbName, String methodName, Date time) {
        System.out.println("SchedulerServlet.scheduleSimpleJob: ejbName: "+ ejbName +" methodname: "+ methodName +" time: "+ time ); //asd
        final String jobName = "quartz job: " + ejbName + "." + methodName;
        SimpleTrigger simpleTrigger = new SimpleTrigger(jobName, "Quartz Trigger", time);
        try {
            scheduleJob(ejbName, methodName, simpleTrigger, "-simple");
        } catch (Exception ex) {
        System.out.println("STATE : " + "scheduleSimpleJob fonksiyonunda hata var.") ;
            Logger.getLogger(SchedulerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void scheduleJob (String ejbName, String methodName, Trigger trigger, String tail) throws SchedulerException {
        try {
            final String jobName = "quartz job: " + ejbName + "." + methodName + tail;
            JobDetail jd = new JobDetail(jobName , "Quartz Job", GFv3EJBInvokerJob.class);
            jd.getJobDataMap().put("ejb", "java:module/"+ejbName);
            jd.getJobDataMap().put("method", methodName);
            System.out.println("SchedulerServlet.scheduleJob: ejbName: "+ ejbName +" methodname: "+ methodName +" trigger: "+ trigger +" tail: "+tail); //asd
            Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
            sched.scheduleJob(jd, trigger);
            Logger.getLogger(SchedulerServlet.class.getName()).log(Level.INFO, null, jobName + " is scheduled...");
    } catch ( Exception ex ) {
        System.out.println("STATE : " + "scheduleJob fonksiyonunda hata var.") ;
    }
    }


    @Override
    public synchronized void init(ServletConfig config) throws ServletException {

        if (!isLoaded) {
            super.init(config);
            System.out.println("SchedulerServlet.init: "+config.toString()); //asd
            scheduleCronJob("OFReportTimeoutService", "ofTimeout", "*/15 * * * * ?");//Seconds, Minutes, Hours, Day of month, Month, Day of week, Year

            scheduleCronJob("ScheduledReportTimeoutService", "protectionInformationTimeout", "0 0 */3 * * ?");
            Calendar now = new GregorianCalendar();
            if (!(now.get(Calendar.HOUR)%3 == 2 && now.get(Calendar.MINUTE) > 40)) {
                now.add(Calendar.MINUTE, 5);
                scheduleSimpleJob("ScheduledReportTimeoutService", "protectionInformationTimeout", now.getTime());
            }

            scheduleCronJob("ScheduledReportTimeoutService", "dailyTimeout", "0 0 4 * * ?");

            scheduleCronJob("ScheduledReportTimeoutService", "weeklyTimeout", "0 15 4 ? * MON");

            scheduleCronJob("ScheduledReportTimeoutService", "monthlyTimeout", "0 0 4 1 * ?");

            scheduleCronJob("ScheduledReportTimeoutService", "yearlyTimeout", "0 0 4 1 1 ?");

            isLoaded = Boolean.TRUE;
        }
        else {
            System.out.println("STATE : " + "synchronized isn't running. isLoaded = TRUE") ;
            System.out.println("STATE : " + "OFReportTimeoutService and protectionInformationTimeout services can't run.") ;
            System.out.println("STATE : " + "synchronized isn't running. ") ;
            Logger.getLogger(SchedulerServlet.class.getName()).log(Level.SEVERE, null, " isn't scheduled...");
        }
    }
}

Но самое интересное, когда я меняю порядок линий цветения

    scheduleCronJob("ScheduledReportTimeoutService", "dailyTimeout", "0 0 4 * * ?");

    scheduleCronJob("ScheduledReportTimeoutService", "weeklyTimeout", "0 15 4 ? * MON");

    scheduleCronJob("ScheduledReportTimeoutService", "monthlyTimeout", "0 0 4 1 * ?");

    scheduleCronJob("ScheduledReportTimeoutService", "yearlyTimeout", "0 0 4 1 1 ?");

Как это

    scheduleCronJob("ScheduledReportTimeoutService", "weeklyTimeout", "0 15 4 ? * MON");

    scheduleCronJob("ScheduledReportTimeoutService", "dailyTimeout", "0 0 4 * * ?");

    scheduleCronJob("ScheduledReportTimeoutService", "monthlyTimeout", "0 0 4 1 * ?");

    scheduleCronJob("ScheduledReportTimeoutService", "yearlyTimeout", "0 0 4 1 1 ?");

Все функции срабатывают, когда приходит время. Есть ли в этом смысл. Просто изменив порядок двух функций, вы заставите код работать. Я что-то упустил?

1 Ответ

0 голосов
/ 28 марта 2012

Я не могу исправить ваш код, но это то, что сработало для меня в моем проекте.Я использовал Quartz для планирования двух разных событий с помощью выражения Cron, которое отправляется через web.xml при запуске сервера. Ниже приведен пример того, что у меня есть.Возможно, вы можете следовать аналогичным строкам, чтобы исправить свой код ... Надеюсь, это поможет.

web.xml entry

    <servlet>
        <servlet-name>QuartzInitializer</servlet-name>
        <servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
      <servlet-name>QuartzServlet</servlet-name>
      <servlet-class>com.xyz.SampleSchedulerServlet</servlet-class>
      <init-param><param-name>firstCronExpr</param-name><param-value>7 0/1 * * * ?</param-value></init-param>
      <init-param><param-name>secondCronExpr</param-name><param-value>7 0/20 * * * ?</param-value></init-param>
        <load-on-startup>2</load-on-startup>   
    </servlet>

Код сервлета1009 *

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

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


public class SampleSchedulerServlet extends GenericServlet {
    private static Logger log = Logger.getLogger(SampleSchedulerServlet.class.getName());

    private static final long serialVersionUID = 1L;
    private static final String FIRST_JOB_NAME   = "First Sample Scheduler Job";
    private static final String FIRST_GROUP_NAME   = "First Sample Scheduler Group";
    private static final String FIRST_TRIGGER_NAME = "First Sample Scheduler Trigger";
    private static final String SECOND_JOB_NAME  = "Second Sample Scheduler Job";
    private static final String SECOND_GROUP_NAME   = "Second Sample Scheduler Group";
    private static final String SECOND_TRIGGER_NAME = "Second Sample Scheduler Trigger";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        log.log(Level.INFO, "Invoking scheduler for Sample..");
        try {
            String cronExpression = getInitParameter("firstCronExpr");
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();            
            CronTrigger cronTrigger = new CronTrigger(FIRST_TRIGGER_NAME, FIRST_GROUP_NAME, cronExpression);
            JobDetail jobDetail = new JobDetail(FIRST_JOB_NAME, FIRST_GROUP_NAME, SomeClass.class);
            scheduler.scheduleJob(jobDetail, cronTrigger);

            cronExpression = getInitParameter("secondCronExpr");
            scheduler = StdSchedulerFactory.getDefaultScheduler(); 
            cronTrigger = new CronTrigger(SECOND_TRIGGER_NAME, SECOND_GROUP_NAME, cronExpression);
            jobDetail = new JobDetail(SECOND_JOB_NAME, SECOND_GROUP_NAME, SomeClass.class);
            scheduler.scheduleJob(jobDetail, cronTrigger);

            log.log(Level.INFO, "Sample Timer scheduled...");           
        } catch (Exception e) {
            log.log(Level.SEVERE, "Problem invoking SampleSchedulerServlet to schedule the Sample jobs..");
            e.printStackTrace();
        }
    }

    public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
    }

    public String getServletInfo() {
        return null;
    }

    public void destroy() {
        try {
            Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
            sched.shutdown();
            log.log(Level.INFO, "Shutting down Sample scheduler - Successful !");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Shutting down Sample scheduler - FAILED !");
            e.printStackTrace();
        }
    }
}
...