protected void update(
      Scheduler scheduler,
      com.liferay.portal.kernel.scheduler.Trigger trigger,
      StorageType storageType)
      throws Exception {

    Trigger quartzTrigger = getQuartzTrigger(trigger, storageType);

    if (quartzTrigger == null) {
      return;
    }

    TriggerKey triggerKey = quartzTrigger.getKey();

    if (scheduler.getTrigger(triggerKey) != null) {
      scheduler.rescheduleJob(triggerKey, quartzTrigger);
    } else {
      JobKey jobKey = quartzTrigger.getJobKey();

      JobDetail jobDetail = scheduler.getJobDetail(jobKey);

      if (jobDetail == null) {
        return;
      }

      synchronized (this) {
        scheduler.deleteJob(jobKey);
        scheduler.scheduleJob(jobDetail, quartzTrigger);
      }

      updateJobState(scheduler, jobKey, TriggerState.NORMAL, true);
    }
  }
  @Override
  public void schedule(
      String name, Date startTime, Date endTime, int repeatCount, long repeatInterval) {
    if (name == null || name.trim().equals("")) {
      name = UUID.randomUUID().toString();
    }

    try {
      scheduler.addJob(jobDetail, true);

      SimpleTrigger SimpleTrigger =
          new SimpleTrigger(
              name,
              Scheduler.DEFAULT_GROUP,
              jobDetail.getName(),
              Scheduler.DEFAULT_GROUP,
              startTime,
              endTime,
              repeatCount,
              repeatInterval);
      scheduler.scheduleJob(SimpleTrigger);
      scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, SimpleTrigger);

    } catch (SchedulerException e) {
      throw new RuntimeException(e);
    }
  }
Example #3
0
 /** 重新调度作业. */
 public void rescheduleJob(final String cronExpression) {
   try {
     scheduler.rescheduleJob(
         TriggerKey.triggerKey(
             Joiner.on("_").join(jobConfiguration.getJobName(), CRON_TRIGGER_INDENTITY_SUFFIX)),
         createTrigger(cronExpression));
   } catch (final SchedulerException ex) {
     throw new JobException(ex);
   }
 }
 /**
  * reschedule the job associated with the given old trigger with the new trigger.
  *
  * @param oldTriggerName - the name of the trigger to remove.
  * @param oldTriggerGroup - the group of the trigger to remove.
  * @param newTrigger - the new Trigger to associate the job with
  */
 @Override
 public void rescheduleAJob(String oldTriggerName, String oldTriggerGroup, Trigger newTrigger) {
   try {
     if (!sched.isShutdown()) {
       sched.rescheduleJob(triggerKey(oldTriggerName, oldTriggerGroup), newTrigger);
     }
   } catch (SchedulerException se) {
     log.error("failed to reschedule the job: {}", se.getMessage());
     log.debug("Exception", se);
   }
 }
Example #5
0
 /**
  * 修改一个任务的触发时间
  *
  * @param triggerName
  * @param triggerGroupName
  * @param time
  * @throws SchedulerException
  * @throws ParseException
  */
 public void modifyJobTime(String triggerName, String triggerGroupName)
     throws SchedulerException, ParseException {
   Scheduler sched = sf.getScheduler();
   Trigger trigger = sched.getTrigger(triggerName, triggerGroupName);
   if (trigger != null) {
     /* CronTrigger  ct = (CronTrigger)trigger;
     //修改时间
     ct.setCronExpression(time);*/
     SimpleTrigger st = triggerManager.setSimpleTrigger((SimpleTrigger) trigger);
     // 重启触发器
     // sched.resumeTrigger(triggerName,triggerGroupName);
     sched.rescheduleJob(triggerName, triggerGroupName, st);
   }
 }
  @Override
  public void schedule(String name, CronExpression cronExpression) {
    if (name == null || name.trim().equals("")) {
      name = UUID.randomUUID().toString();
    }

    try {
      scheduler.addJob(jobDetail, true);

      CronTrigger cronTrigger =
          new CronTrigger(
              name, Scheduler.DEFAULT_GROUP, jobDetail.getName(), Scheduler.DEFAULT_GROUP);
      cronTrigger.setCronExpression(cronExpression);
      scheduler.scheduleJob(cronTrigger);
      scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, cronTrigger);
    } catch (SchedulerException e) {
      throw new RuntimeException(e);
    }
  }
 public void submit(final Scheduler scheduler) throws SchedulerException {
   scheduler.rescheduleJob(trigger.getKey(), getTrigger());
 }
Example #8
0
  public void run() throws Exception {
    Logger log = LoggerFactory.getLogger(SimpleTriggerExample.class);

    log.info("------- Initializing -------------------");
    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    log.info("------- Initialization Complete --------");
    log.info("------- Scheduling Jobs ----------------");

    // jobs can be scheduled before sched.start() has been called
    // get a "nice round" time a few seconds in the future...
    long ts = TriggerUtils.getNextGivenSecondDate(null, 5).getTime();

    sched.start();
    log.info("------- Started Scheduler -----------------");

    // jobs can also be scheduled after start() has been called...
    // job7 will repeat 20 times, repeat every 3 sec
    JobDetail job = new JobDetail("job7", "group1", SimpleJob.class);
    SimpleTrigger trigger =
        new SimpleTrigger("trigger7", "group1", "job7", "group1", new Date(ts), null, 30, 2000L);
    Date ft = sched.scheduleJob(job, trigger);
    log.info(
        job.getFullName()
            + " will run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    log.info("------- Waiting 15 seconds... --------------");
    try {
      Thread.sleep(15L * 1000L);
    } catch (Exception e) {
    }

    // jobs can be re-scheduled...
    // job 7 will run immediately and repeat 10 times for every second
    log.info("------- Rescheduling... --------------------");
    trigger =
        new SimpleTrigger("trigger7", "group1", "job7", "group1", new Date(), null, 10, 1000L);
    ft = sched.rescheduleJob("trigger7", "group1", trigger);
    log.info("job7 rescheduled to run at: " + ft);

    log.info("------- Waiting five minutes... ------------");
    try {
      Thread.sleep(300L * 1000L);
    } catch (Exception e) {
    }

    log.info("------- Shutting Down ---------------------");
    sched.shutdown(true);
    log.info("------- Shutdown Complete -----------------");

    // display some stats about the schedule that just ran
    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
  }
  public void run() throws Exception {
    Logger log = LoggerFactory.getLogger(SimpleTriggerExample.class);

    log.info("------- Initializing -------------------");

    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    log.info("------- Initialization Complete --------");

    log.info("------- Scheduling Jobs ----------------");

    // jobs can be scheduled before sched.start() has been called

    // get a "nice round" time a few seconds in the future...
    Date startTime = DateBuilder.nextGivenSecondDate(null, 15);

    // job1 will only fire once at date/time "ts"
    JobDetail job = newJob(SimpleJob.class).withIdentity("job1", "group1").build();

    SimpleTrigger trigger =
        (SimpleTrigger) newTrigger().withIdentity("trigger1", "group1").startAt(startTime).build();

    // schedule it to run!
    Date ft = sched.scheduleJob(job, trigger);
    log.info(
        job.getKey()
            + " will run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    // job2 will only fire once at date/time "ts"
    job = newJob(SimpleJob.class).withIdentity("job2", "group1").build();

    trigger =
        (SimpleTrigger) newTrigger().withIdentity("trigger2", "group1").startAt(startTime).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(
        job.getKey()
            + " will run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    // job3 will run 11 times (run once and repeat 10 more times)
    // job3 will repeat every 10 seconds
    job = newJob(SimpleJob.class).withIdentity("job3", "group1").build();

    trigger =
        newTrigger()
            .withIdentity("trigger3", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(10))
            .build();

    ft = sched.scheduleJob(job, trigger);
    log.info(
        job.getKey()
            + " will run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    // the same job (job3) will be scheduled by a another trigger
    // this time will only repeat twice at a 70 second interval

    trigger =
        newTrigger()
            .withIdentity("trigger3", "group2")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(2))
            .forJob(job)
            .build();

    ft = sched.scheduleJob(trigger);
    log.info(
        job.getKey()
            + " will [also] run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    // job4 will run 6 times (run once and repeat 5 more times)
    // job4 will repeat every 10 seconds
    job = newJob(SimpleJob.class).withIdentity("job4", "group1").build();

    trigger =
        newTrigger()
            .withIdentity("trigger4", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(5))
            .build();

    ft = sched.scheduleJob(job, trigger);
    log.info(
        job.getKey()
            + " will run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    // job5 will run once, five minutes in the future
    job = newJob(SimpleJob.class).withIdentity("job5", "group1").build();

    trigger =
        (SimpleTrigger)
            newTrigger()
                .withIdentity("trigger5", "group1")
                .startAt(futureDate(5, IntervalUnit.MINUTE))
                .build();

    ft = sched.scheduleJob(job, trigger);
    log.info(
        job.getKey()
            + " will run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    // job6 will run indefinitely, every 40 seconds
    job = newJob(SimpleJob.class).withIdentity("job6", "group1").build();

    trigger =
        newTrigger()
            .withIdentity("trigger6", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(40).repeatForever())
            .build();

    ft = sched.scheduleJob(job, trigger);
    log.info(
        job.getKey()
            + " will run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    log.info("------- Starting Scheduler ----------------");

    // All of the jobs have been added to the scheduler, but none of the jobs
    // will run until the scheduler has been started
    sched.start();

    log.info("------- Started Scheduler -----------------");

    // jobs can also be scheduled after start() has been called...
    // job7 will repeat 20 times, repeat every five minutes
    job = newJob(SimpleJob.class).withIdentity("job7", "group1").build();

    trigger =
        newTrigger()
            .withIdentity("trigger7", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20))
            .build();

    ft = sched.scheduleJob(job, trigger);
    log.info(
        job.getKey()
            + " will run at: "
            + ft
            + " and repeat: "
            + trigger.getRepeatCount()
            + " times, every "
            + trigger.getRepeatInterval() / 1000
            + " seconds");

    // jobs can be fired directly... (rather than waiting for a trigger)
    job = newJob(SimpleJob.class).withIdentity("job8", "group1").storeDurably().build();

    sched.addJob(job, true);

    log.info("'Manually' triggering job8...");
    sched.triggerJob(jobKey("job8", "group1"));

    log.info("------- Waiting 30 seconds... --------------");

    try {
      // wait 33 seconds to show jobs
      Thread.sleep(30L * 1000L);
      // executing...
    } catch (Exception e) {
    }

    // jobs can be re-scheduled...
    // job 7 will run immediately and repeat 10 times for every second
    log.info("------- Rescheduling... --------------------");
    trigger =
        newTrigger()
            .withIdentity("trigger7", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20))
            .build();

    ft = sched.rescheduleJob(trigger.getKey(), trigger);
    log.info("job7 rescheduled to run at: " + ft);

    log.info("------- Waiting five minutes... ------------");
    try {
      // wait five minutes to show jobs
      Thread.sleep(300L * 1000L);
      // executing...
    } catch (Exception e) {
    }

    log.info("------- Shutting Down ---------------------");

    sched.shutdown(true);

    log.info("------- Shutdown Complete -----------------");

    // display some stats about the schedule that just ran
    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
  }
  /**
   * Schedules a given job and trigger (both wrapped by a <code>JobSchedulingBundle</code>).
   *
   * @param job job wrapper.
   * @param sched job scheduler.
   * @param localOverWriteExistingJobs locally overwrite existing jobs.
   * @exception SchedulerException if the Job or Trigger cannot be added to the Scheduler, or there
   *     is an internal Scheduler error.
   */
  public void scheduleJob(
      JobSchedulingBundle job, Scheduler sched, boolean localOverWriteExistingJobs)
      throws SchedulerException {
    if ((job != null) && job.isValid()) {
      JobDetail detail = job.getJobDetail();

      JobDetail dupeJ = sched.getJobDetail(detail.getName(), detail.getGroup());

      if ((dupeJ != null) && !localOverWriteExistingJobs) {
        getLog().info("Not overwriting existing job: " + dupeJ.getFullName());
        return;
      }

      if (dupeJ != null) {
        getLog().info("Replacing job: " + detail.getFullName());
      } else {
        getLog().info("Adding job: " + detail.getFullName());
      }

      if (job.getTriggers().size() == 0 && !job.getJobDetail().isDurable()) {
        if (dupeJ == null) {
          throw new SchedulerException(
              "A new job defined without any triggers must be durable: " + detail.getFullName());
        }

        if ((dupeJ.isDurable()
            && (sched.getTriggersOfJob(detail.getName(), detail.getGroup()).length == 0))) {
          throw new SchedulerException(
              "Can't make a durable job without triggers non-durable: " + detail.getFullName());
        }
      }

      sched.addJob(detail, true);

      for (Iterator iter = job.getTriggers().iterator(); iter.hasNext(); ) {
        Trigger trigger = (Trigger) iter.next();

        trigger.setJobName(detail.getName());
        trigger.setJobGroup(detail.getGroup());

        if (trigger.getStartTime() == null) {
          trigger.setStartTime(new Date());
        }

        boolean addedTrigger = false;
        while (addedTrigger == false) {
          Trigger dupeT = sched.getTrigger(trigger.getName(), trigger.getGroup());
          if (dupeT != null) {
            if (getLog().isDebugEnabled()) {
              getLog()
                  .debug(
                      "Rescheduling job: "
                          + detail.getFullName()
                          + " with updated trigger: "
                          + trigger.getFullName());
            }
            if (!dupeT.getJobGroup().equals(trigger.getJobGroup())
                || !dupeT.getJobName().equals(trigger.getJobName())) {
              getLog().warn("Possibly duplicately named triggers in jobs xml file!");
            }
            sched.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger);
          } else {
            if (getLog().isDebugEnabled()) {
              getLog()
                  .debug(
                      "Scheduling job: "
                          + detail.getFullName()
                          + " with trigger: "
                          + trigger.getFullName());
            }

            try {
              sched.scheduleJob(trigger);
            } catch (ObjectAlreadyExistsException e) {
              if (getLog().isDebugEnabled()) {
                getLog()
                    .debug(
                        "Adding trigger: "
                            + trigger.getFullName()
                            + " for job: "
                            + detail.getFullName()
                            + " failed because the trigger already existed.  "
                            + "This is likely due to a race condition between multiple instances "
                            + "in the cluster.  Will try to reschedule instead.");
              }
              continue;
            }
          }
          addedTrigger = true;
        }
      }

      addScheduledJob(job);
    }
  }
  @RequestMapping("/cancelScheduledJob")
  public String cancelScheduledJob(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam("theJobName") String theJobName,
      @RequestParam("theJobGroupName") String theJobGroupName,
      @RequestParam("theTriggerName") String triggerName,
      @RequestParam("theTriggerGroupName") String triggerGroupName,
      @RequestParam("redirection") String redirection,
      ModelMap model)
      throws SchedulerException {

    scheduler.getJobDetail(theJobName, theJobGroupName);
    logger.debug("About to pause the job-->" + theJobName + "Job Group Name -->" + theJobGroupName);

    SimpleTrigger oldTrigger = (SimpleTrigger) scheduler.getTrigger(triggerName, triggerGroupName);
    if (oldTrigger != null) {
      Date startTime =
          new Date(oldTrigger.getStartTime().getTime() + oldTrigger.getRepeatInterval());
      if (triggerGroupName.equals(ExtractController.TRIGGER_GROUP_NAME)) {
        interruptQuartzJob(scheduler, theJobName, theJobGroupName);
      }

      scheduler.pauseJob(theJobName, theJobGroupName);

      SimpleTrigger newTrigger = new SimpleTrigger(triggerName, triggerGroupName);
      newTrigger.setJobName(theJobName);
      newTrigger.setJobGroup(theJobGroupName);
      newTrigger.setJobDataMap(oldTrigger.getJobDataMap());
      newTrigger.setVolatility(false);
      newTrigger.setRepeatCount(oldTrigger.getRepeatCount());
      newTrigger.setRepeatInterval(oldTrigger.getRepeatInterval());
      newTrigger.setMisfireInstruction(
          SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);
      newTrigger.setStartTime(startTime);
      newTrigger.setRepeatInterval(oldTrigger.getRepeatInterval());

      scheduler.unscheduleJob(
          triggerName,
          triggerGroupName); // these are the jobs which are from extract data and are not not
      // required to be rescheduled.

      ArrayList<String> pageMessages = new ArrayList<String>();

      if (triggerGroupName.equals(ExtractController.TRIGGER_GROUP_NAME)) {
        scheduler.rescheduleJob(triggerName, triggerGroupName, newTrigger);

        pageMessages.add("The Job  " + theJobName + " has been cancelled");
      } else if (triggerGroupName.equals(XsltTriggerService.TRIGGER_GROUP_NAME)) {

        JobDetailBean jobDetailBean = new JobDetailBean();
        jobDetailBean.setGroup(XsltTriggerService.TRIGGER_GROUP_NAME);
        jobDetailBean.setName(newTrigger.getName());
        jobDetailBean.setJobClass(org.akaza.openclinica.job.XsltStatefulJob.class);
        jobDetailBean.setJobDataMap(newTrigger.getJobDataMap());
        jobDetailBean.setDurability(true); // need durability?
        jobDetailBean.setVolatility(false);

        scheduler.deleteJob(theJobName, theJobGroupName);
        scheduler.scheduleJob(jobDetailBean, newTrigger);
        pageMessages.add("The Job " + theJobName + "  has been rescheduled");
      }

      request.setAttribute("pageMessages", pageMessages);

      logger.debug("jobDetails>" + scheduler.getJobDetail(theJobName, theJobGroupName));
    }
    sdvUtil.forwardRequestFromController(request, response, "/pages/" + redirection);
    return null;
  }
  /** Initialize each job. */
  protected void initializeJobs(Session jcrSession) {
    Collection<KKStoreConfig> kkStoreConfigs =
        HippoModuleConfig.getConfig().getStoresConfig().values();

    if (kkStoreConfigs.size() == 0) {
      log.error("No store config has been found. Please check the konakart:konakart configuration");
      return;
    }

    // Get the first one.
    KKStoreConfig kkStoreConfig = kkStoreConfigs.iterator().next();

    try {
      String triggerName = MASS_SYNC_JOB_TRIGGER;
      String jobName = MASS_SYNC_JOB_ONCE;

      JobDetail jobDetail =
          new JobDetail(jobName, MASS_SYNC_JOB_GROUP, Class.forName(kkStoreConfig.getJobClass()));

      JobDataMap dataMap = new JobDataMap();
      jobDetail.setJobDataMap(dataMap);

      // Create a trigger that fires immediately, and run only once
      Trigger trigger = new SimpleTrigger(MASS_SYNC_JOB_TRIGGER_ONCE);
      trigger.setStartTime(new Date(System.currentTimeMillis() + 10000));

      if (!triggerExists(trigger)) {
        resourceScheduler.scheduleJob(jobDetail, trigger);
      }

      jobName = MASS_SYNC_JOB;
      jobDetail =
          new JobDetail(jobName, MASS_SYNC_JOB_GROUP, Class.forName(kkStoreConfig.getJobClass()));

      // Create the cron task. The first launch is scheduled after 30 minutes
      if (StringUtils.isNotEmpty(kkStoreConfig.getCronExpression())) {
        trigger =
            new CronTrigger(
                triggerName,
                MASS_SYNC_JOB_TRIGGER_GROUP,
                jobName,
                MASS_SYNC_JOB_GROUP,
                kkStoreConfig.getCronExpression());

        trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));

        if (triggerExists(trigger)) {
          if (triggerChanged(trigger)) {
            resourceScheduler.rescheduleJob(
                MASS_SYNC_JOB_TRIGGER, MASS_SYNC_JOB_TRIGGER_GROUP, trigger);
          }
        } else {
          resourceScheduler.scheduleJob(jobDetail, trigger);
        }
      }

    } catch (ClassNotFoundException e) {
      log.error("Failed to find the Job class named - " + kkStoreConfig.getJobClass(), e);
    } catch (ParseException e) {
      log.error("Failed to parse the cron expression - " + kkStoreConfig.getCronExpression(), e);
    } catch (SchedulerException e) {
      log.error("Failed to start the job", e);
    }
  }
 /**
  * 重新调度作业.
  *
  * @throws SchedulerException
  */
 public void rescheduleJob(final String cronExpression) throws SchedulerException {
   scheduler.rescheduleJob(
       TriggerKey.triggerKey(jobConfiguration.getJobName()), createTrigger(cronExpression));
 }