public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec)
      throws ResourceException {
    log.debug("endpointActivation, spec=" + spec);
    QuartzActivationSpec quartzSpec = (QuartzActivationSpec) spec;

    // allocate instance of endpoint to figure out its endpoint interface
    Class clazz = QuartzJob.class;
    MessageEndpoint tmpMe = endpointFactory.createEndpoint(null);
    if (tmpMe instanceof StatefulJob) clazz = StatefulQuartzJob.class;
    tmpMe.release();

    try {
      JobDetail jobDetail =
          new JobDetail(
              quartzSpec.getJobName(), quartzSpec.getJobGroup(), clazz, true, false, false);
      jobDetail.getJobDataMap().setAllowsTransientData(true);
      jobDetail.getJobDataMap().put("endpointFactory", endpointFactory);
      log.debug("adding job: " + quartzSpec);
      CronTrigger trigger =
          new CronTrigger(
              quartzSpec.getTriggerName(),
              quartzSpec.getTriggerGroup(),
              quartzSpec.getCronTrigger());
      sched.scheduleJob(jobDetail, trigger);
    } catch (Exception e) {
      log.error(e);
      throw new ResourceException(e);
    }
  }
  /**
   * schedule a job
   *
   * @param aScheduler scheduler to start
   * @throws SchedulerException
   */
  public static void schedule(am.projects.webserver.report.vo.Scheduler aScheduler)
      throws SchedulerException {

    if (null == scheduler) return;

    JobDataMap dataMap = new JobDataMap();
    dataMap.put(am.projects.webserver.report.vo.Scheduler.class.getSimpleName(), aScheduler);

    // define the job and tie it to our HelloJob class
    String jobName = buildJobName(aScheduler);
    String groupName = buildJobGroupName(aScheduler);
    JobKey jobKey = new JobKey(jobName, groupName);

    JobDetail job = newJob(MonitorJob.class).withIdentity(jobKey).usingJobData(dataMap).build();

    TriggerKey triggerKey = new TriggerKey(jobName, groupName);
    Trigger trigger =
        newTrigger()
            .withIdentity(triggerKey)
            .startNow()
            .withSchedule(
                simpleSchedule()
                    .withIntervalInMinutes(aScheduler.getRequestRepeatIntervalInMinutes())
                    .repeatForever())
            .build();

    scheduler.scheduleJob(job, trigger);
  }
  private void startScheduler() {
    SchedulerFactory sf = new StdSchedulerFactory();
    try {
      sched = sf.getScheduler();

      JobDetail notificationCleanupJob =
          newJob(NotificationCleanupJob.class)
              .withIdentity("notificationCleanupJob", "chatServer")
              .build();

      CronTrigger notificationTrigger =
          newTrigger()
              .withIdentity("notificationTrigger", "chatServer")
              .withSchedule(
                  cronSchedule(
                      PropertyManager.getProperty(PropertyManager.PROPERTY_CRON_NOTIF_CLEANUP)))
              .build();

      sched.scheduleJob(notificationCleanupJob, notificationTrigger);

      sched.start();

      log.info("Scheduler Started");

    } catch (SchedulerException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
  /**
   * Schedule a job to start at a fixed point of time and repeat with interval period.
   *
   * @param job the job to schedule
   * @param startTime the start time
   * @param interval the repeat interval in seconds
   */
  public void scheduleAtWithInterval(
      final org.easybatch.core.job.Job job, final Date startTime, final int interval)
      throws JobSchedulerException {
    checkNotNull(job, "job");
    checkNotNull(startTime, "startTime");

    String executionId = job.getExecutionId();
    String jobName = JOB_NAME_PREFIX + executionId;
    String triggerName = TRIGGER_NAME_PREFIX + executionId;

    ScheduleBuilder scheduleBuilder =
        simpleSchedule().withIntervalInSeconds(interval).repeatForever();

    Trigger trigger =
        newTrigger()
            .withIdentity(triggerName)
            .startAt(startTime)
            .withSchedule(scheduleBuilder)
            .forJob(jobName)
            .build();

    JobDetail jobDetail = getJobDetail(job, jobName);

    try {
      LOGGER.log(
          Level.INFO,
          "Scheduling job {0} to start at {1} and every {2} second(s)",
          new Object[] {job, startTime, interval});
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      throw new JobSchedulerException("Unable to schedule job " + job, e);
    }
  }
 private void scheduleAllJobsOnApplicationStop() throws SchedulerException {
   List<Class<? extends Job>> stopJobClasses = getJobClasses(OnApplicationStop.class);
   for (Class<? extends Job> clazz : stopJobClasses) {
     JobBuilder jobDetail = JobBuilder.newJob(clazz);
     scheduler.scheduleJob(jobDetail.build(), executeNowTrigger());
   }
 }
示例#6
0
 public void scheduleJob(JobDetail jobDetail, Trigger trigger) {
   try {
     scheduler.scheduleJob(jobDetail, trigger);
   } catch (SchedulerException ex) {
     Error.SCHEDULE_JOB.record().create(ex);
   }
 }
示例#7
0
  private void scheduleCronJob(String cronString, String elementId) {
    try {
      SchedulerFactory schedulerFactory = new StdSchedulerFactory();
      scheduler = schedulerFactory.getScheduler();
      scheduler.start();

      JobDataMap dataMap = new JobDataMap();
      dataMap.put("trigger", this);

      jobName = "TriggerJob_" + elementId;
      JobDetail job =
          org.quartz.JobBuilder.newJob(CronEventTrigger.class)
              .withIdentity(jobName, jobGroup)
              .usingJobData(dataMap)
              .build();

      Trigger trigger =
          org.quartz.TriggerBuilder.newTrigger()
              .withIdentity("TriggerJob_" + elementId, jobGroup)
              .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
              .build();

      scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
      log.error(
          "Error while instantiating quartz scheduler for trigger '"
              + triggerDefinition.getId()
              + "',"
              + e.getMessage(),
          e);
    }
  }
  /**
   * Schedule a job with a unix-like cron expression.
   *
   * @param job the job to schedule
   * @param cronExpression the cron expression to use. For a complete tutorial about cron
   *     expressions, please refer to <a
   *     href="http://quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/crontrigger">quartz
   *     reference documentation</a>.
   */
  public void scheduleCron(final org.easybatch.core.job.Job job, final String cronExpression)
      throws JobSchedulerException {
    checkNotNull(job, "job");
    checkNotNull(cronExpression, "cronExpression");

    String executionId = job.getExecutionId();
    String jobName = JOB_NAME_PREFIX + executionId;
    String triggerName = TRIGGER_NAME_PREFIX + executionId;

    Trigger trigger =
        newTrigger()
            .withIdentity(triggerName)
            .withSchedule(cronSchedule(cronExpression))
            .forJob(jobName)
            .build();

    JobDetail jobDetail = getJobDetail(job, jobName);

    try {
      LOGGER.log(
          Level.INFO,
          "Scheduling job {0} with cron expression {1}",
          new Object[] {job, cronExpression});
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      throw new JobSchedulerException("Unable to schedule job " + job, e);
    }
  }
  public void quartzTest() throws Exception {

    JobDetail jobDetail =
        JobBuilder.newJob(QuartsDemo.class).withIdentity("testJob_1", "group_1").build();

    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withIdentity("trigger_1", "group_1")
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(1) // 时间间隔
                    .withRepeatCount(10) // 重复次数(将执行 10 次/ or //调用10次)
                )
            .build();
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    sched.scheduleJob(jobDetail, trigger);

    sched.start();

    Thread.currentThread().sleep(20000);

    System.err.println("关闭  ");
    sched.shutdown();
  }
  /** QTZ-205 */
  @Test
  public void testTriggerFinalized() throws Exception {
    Qtz205TriggerListener triggerListener = new Qtz205TriggerListener();
    Qtz205ScheListener schedulerListener = new Qtz205ScheListener();
    Properties props = new Properties();
    props.setProperty("org.quartz.scheduler.idleWaitTime", "1500");
    props.setProperty("org.quartz.threadPool.threadCount", "2");
    Scheduler scheduler = new StdSchedulerFactory(props).getScheduler();
    scheduler.getListenerManager().addSchedulerListener(schedulerListener);
    scheduler.getListenerManager().addTriggerListener(triggerListener);
    scheduler.start();
    scheduler.standby();

    JobDetail job = newJob(Qtz205Job.class).withIdentity("test").build();
    Trigger trigger =
        newTrigger()
            .withIdentity("test")
            .withSchedule(simpleSchedule().withIntervalInMilliseconds(250).withRepeatCount(2))
            .build();
    scheduler.scheduleJob(job, trigger);
    scheduler.start();
    Thread.sleep(5000);

    scheduler.shutdown(true);

    Assert.assertEquals(2, Qtz205Job.jobExecutionCount);
    Assert.assertEquals(3, triggerListener.getFireCount());
    Assert.assertEquals(1, schedulerListener.getTriggerFinalizedCount());
  }
示例#11
0
  public void testCreation() throws Exception {
    Scheduler scheduler = (Scheduler) lookup(Scheduler.ROLE, "test");

    assertNotNull(scheduler);

    JobDataMap dataMap = new JobDataMap();

    dataMap.put("project", "continuum");

    JobDetail jobDetail = new JobDetail("job", "group", JobOne.class);

    jobDetail.setJobDataMap(dataMap);

    Trigger trigger = new SimpleTrigger("trigger", "group");

    scheduler.addGlobalTriggerListener(this);

    scheduler.scheduleJob(jobDetail, trigger);

    while (!triggerFired) {
      // System.out.println("! triggerFired");
      Thread.sleep(10);
    }
    System.out.println("ok triggerFired");
  }
 private void scheduleAllJobsOnApplicationStart() throws SchedulerException {
   List<Class<? extends Job>> startJobClasses = getJobClasses(OnApplicationStart.class);
   log.info("Jobs to run on application start: " + startJobClasses);
   for (Class<? extends org.quartz.Job> clazz : startJobClasses) {
     JobBuilder jobBuilder = JobBuilder.newJob(clazz);
     scheduler.scheduleJob(jobBuilder.build(), executeNowTrigger());
   }
 }
  private void scheduleAllJobsWithOnAnnotation() throws SchedulerException {
    List<Class<? extends Job>> onJobClasses = getJobClasses(On.class);
    log.info("Jobs with @On annotation: " + onJobClasses);

    for (Class<? extends org.quartz.Job> clazz : onJobClasses) {
      On annotation = clazz.getAnnotation(On.class);

      CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(annotation.value());
      Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build();
      JobBuilder jobBuilder = JobBuilder.newJob(clazz);
      scheduler.scheduleJob(jobBuilder.build(), trigger);
    }
  }
  private void scheduleAllJobsWithEveryAnnotation() throws SchedulerException {
    List<Class<? extends Job>> everyJobClasses = getJobClasses(Every.class);
    log.info("Jobs with @Every annotation: " + everyJobClasses);

    for (Class<? extends org.quartz.Job> clazz : everyJobClasses) {
      Every annotation = clazz.getAnnotation(Every.class);
      int secondDelay = TimeParserUtil.parseDuration(annotation.value());
      SimpleScheduleBuilder scheduleBuilder =
          SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(secondDelay).repeatForever();
      Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build();

      JobBuilder jobBuilder = JobBuilder.newJob(clazz);
      scheduler.scheduleJob(jobBuilder.build(), trigger);
    }
  }
 @Override
 public ScheduleToken schedule(Instant triggerDateTime, Object event) {
   Assert.state(initialized, () -> "Scheduler is not yet initialized");
   EventMessage eventMessage = GenericEventMessage.asEventMessage(event);
   String jobIdentifier = JOB_NAME_PREFIX + eventMessage.getIdentifier();
   QuartzScheduleToken tr = new QuartzScheduleToken(jobIdentifier, groupIdentifier);
   try {
     JobDetail jobDetail =
         buildJobDetail(eventMessage, new JobKey(jobIdentifier, groupIdentifier));
     scheduler.scheduleJob(jobDetail, buildTrigger(triggerDateTime, jobDetail.getKey()));
   } catch (SchedulerException e) {
     throw new SchedulingException("An error occurred while setting a timer for a saga", e);
   }
   return tr;
 }
示例#16
0
 /**
  * 从Scheduler 移除当前的Job,修改Trigger
  *
  * @param jobDetail
  * @param time
  * @throws SchedulerException
  * @throws ParseException
  */
 public static void modifyJobTime(JobDetail jobDetail, String time)
     throws SchedulerException, ParseException {
   Scheduler sched = sf.getScheduler();
   Trigger trigger = sched.getTrigger(jobDetail.getName(), TRIGGER_GROUP_NAME);
   if (trigger != null) {
     CronTrigger ct = (CronTrigger) trigger;
     // 移除当前进程的Job
     sched.deleteJob(jobDetail.getName(), jobDetail.getGroup());
     // 修改Trigger
     ct.setCronExpression(time);
     System.out.println("CronTrigger getName " + ct.getJobName());
     // 重新调度jobDetail
     sched.scheduleJob(jobDetail, ct);
   }
 }
示例#17
0
  public boolean start() {

    try {
      scheduler.start();
    } catch (SchedulerException e) {
      throw new SynapseException("Error starting the scheduler", e);
    }

    Trigger trigger;
    TriggerBuilder<Trigger> triggerBuilder = newTrigger().withIdentity(name + "-trigger");

    if (cronExpression == null || "".equals(cronExpression)) {
      trigger =
          triggerBuilder
              .withSchedule(
                  simpleSchedule()
                      .withIntervalInMilliseconds(interval)
                      .repeatForever()
                      .withMisfireHandlingInstructionNextWithRemainingCount())
              .build();
    } else {
      trigger =
          triggerBuilder
              .startNow()
              .withSchedule(
                  CronScheduleBuilder.cronSchedule(cronExpression)
                      .withMisfireHandlingInstructionDoNothing())
              .build();
    }

    JobDataMap jobDataMap = getJobDataMap();
    jobDataMap.put(MessageProcessorConstants.PARAMETERS, parameters);

    JobBuilder jobBuilder = getJobBuilder();
    JobDetail jobDetail = jobBuilder.usingJobData(jobDataMap).build();

    try {
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      throw new SynapseException(
          "Error scheduling job : " + jobDetail + " with trigger " + trigger, e);
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Started message processor. [" + getName() + "].");
    }

    return true;
  }
 /** This method adds the {@link #JOBKEY_DATABASE_UPDATE_REGULAR} job to the scheduler. */
 public void startRegularDatabaseUpdates() {
   try {
     Trigger trigger = null;
     switch (period) {
       case ServiceConstants.PARAM_VALUE_DAILY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.dailyAtHourAndMinute(atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       case ServiceConstants.PARAM_VALUE_WEEKLY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.weeklyOnDayAndHourAndMinute(dayOfWeek, atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       case ServiceConstants.PARAM_VALUE_MONTHLY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.monthlyOnDayAndHourAndMinute(dayOfMonth, atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       default:
         throw new WebApplicationException(
             Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                 .entity(
                     "Could not initialize trigger for regular database update. Period was not set")
                 .build());
     }
     sched.scheduleJob(trigger);
   } catch (SchedulerException ex) {
     Logger.getLogger(QuartzSchedulerController.class.getName()).log(Level.SEVERE, null, ex);
     throw new WebApplicationException(PreparedServerResponses.ERROR_SCHEDULER);
   }
 }
示例#19
0
  public static void startJob(String jobName, Job job, String time)
      throws SchedulerException, ParseException {
    Scheduler sched = sf.getScheduler();

    JobDetail jobDetail = new JobDetail();
    jobDetail.setName(jobName);
    jobDetail.setGroup(JOB_GROUP_NAME);
    jobDetail.setJobClass(job.getClass());

    CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);
    trigger.setCronExpression(time);
    sched.scheduleJob(jobDetail, trigger);

    if (!sched.isShutdown()) {
      sched.start();
    }
  }
 void startJob(QuartzJob job) {
   assertNotNull(job, "任务不存在");
   JobKey key = createJobKey(job.getId());
   JobDetail jobDetail =
       JobBuilder.newJob(SimpleJob.class)
           .withIdentity(key)
           .setJobData(createJobDataMap(job.getParameters()))
           .usingJobData(SimpleJobFactory.QUARTZ_ID_KEY, job.getId())
           .withDescription(job.getName() + (job.getRemark() == null ? "" : job.getRemark()))
           .build();
   MutableTrigger trigger = CronScheduleBuilder.cronSchedule(job.getCron()).build();
   trigger.setKey(createTriggerKey(job.getId()));
   try {
     scheduler.scheduleJob(jobDetail, trigger);
   } catch (SchedulerException e) {
     throw new BusinessException("创建定时任务失败!", e, 500);
   }
 }
示例#21
0
  private void startJobs() {
    try {
      // Get a new scheduler
      scheduler = new StdSchedulerFactory().getScheduler();
      // Start it up. This won't start any jobs though.
      scheduler.start();

      for (GuanxiJobConfig gxJob : gxJobs) {
        // Need a new JobDetail to hold custom data to send to the job we're controlling
        JobDetail jobDetail =
            new JobDetail(
                gxJob.getKey(), Scheduler.DEFAULT_GROUP, Class.forName(gxJob.getJobClass()));

        // Create a new JobDataMap for custom data to be sent to the job...
        JobDataMap jobDataMap = new JobDataMap();
        // ...and add the job's custom config object
        jobDataMap.put(GuanxiJobConfig.JOB_KEY_JOB_CONFIG, gxJob);

        // Put the job's custom data in it's JobDetail
        jobDetail.setJobDataMap(jobDataMap);

        /* Tell the scheduler when this job will run. Nothing will happen
         * until the start method is called.
         */
        Trigger trigger =
            new CronTrigger(gxJob.getKey(), Scheduler.DEFAULT_GROUP, gxJob.getCronLine());

        // Start the job
        scheduler.scheduleJob(jobDetail, trigger);

        if (gxJob.isStartImmediately()) {
          scheduler.triggerJob(gxJob.getKey(), Scheduler.DEFAULT_GROUP);
        }
      }
    } catch (ClassNotFoundException cnfe) {
      logger.error("Error locating job class", cnfe);
    } catch (SchedulerException se) {
      logger.error("Job scheduling error", se);
    } catch (ParseException pe) {
      logger.error("Error parsing job cronline", pe);
    }
  }
  private void schedulePurgeHistory(int hour, int minutes) throws SchedulerException {

    if (null == scheduler) return;

    // define the job and tie it to our HelloJob class
    String jobName = PurgeHistoryJob.class.getSimpleName();
    String groupName = "purges";

    JobKey jobKey = new JobKey(jobName, groupName);
    JobDetail job = newJob(PurgeHistoryJob.class).withIdentity(jobKey).build();

    TriggerKey triggerKey = new TriggerKey(jobName, groupName);
    Trigger trigger =
        newTrigger()
            .withIdentity(triggerKey)
            .withSchedule(dailyAtHourAndMinute(hour, minutes))
            .build();

    scheduler.scheduleJob(job, trigger);
  }
  /**
   * Schedule a job to start at a fixed point of time.
   *
   * @param job the job to schedule
   * @param startTime the start time
   */
  public void scheduleAt(final org.easybatch.core.job.Job job, final Date startTime)
      throws JobSchedulerException {
    checkNotNull(job, "job");
    checkNotNull(startTime, "startTime");

    String executionId = job.getExecutionId();
    String jobName = JOB_NAME_PREFIX + executionId;
    String triggerName = TRIGGER_NAME_PREFIX + executionId;

    Trigger trigger =
        newTrigger().withIdentity(triggerName).startAt(startTime).forJob(jobName).build();

    JobDetail jobDetail = getJobDetail(job, jobName);

    try {
      LOGGER.log(Level.INFO, "Scheduling job {0} to start at {1}", new Object[] {job, startTime});
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      throw new JobSchedulerException("Unable to schedule job " + job, e);
    }
  }
示例#24
0
  private void addEscalationJob(Scheduler scheduler) throws SchedulerException {
    JobDetail oJobDetail_Escalation_Standart =
        new JobDetail(
            "oJobDetail_Escalation_Standart", "oJobDetail_Escalation_Group", JobEscalation.class);

    CronTrigger oCronTrigger_EveryNight_Deep =
        new CronTrigger("oCronTrigger_EveryNight_Deep", "oCronTrigger_EveryNight_Group");
    try {
      LOG.info("oCronExpression__EveryNight_Deep...");
      CronExpression oCronExpression__EveryNight_Deep = new CronExpression("0 0 2 1/1 * ?");
      LOG.info("oCronExpression__EveryNight_Deep.setCronExpression...");
      oCronTrigger_EveryNight_Deep.setCronExpression(oCronExpression__EveryNight_Deep);
    } catch (Exception oException) {
      LOG.error("FAIL: {}", oException.getMessage());
    }
    if (!generalConfig.bTest()) {
      LOG.info("scheduleJob...");
      scheduler.scheduleJob(oJobDetail_Escalation_Standart, oCronTrigger_EveryNight_Deep);
    } else {
      LOG.info("scheduleJob... SKIPED(test)!");
    }
  }
示例#25
0
  public static void main(String[] args) {
    // Configure Job
    JobDetail jobDetail =
        JobBuilder.newJob(HelloWorldJob.class).withIdentity("HelloWorldJob").build();

    // Configure Trigger
    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
            .build();

    // Start Scheduler
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    try {
      Scheduler scheduler = schedulerFactory.getScheduler();
      scheduler.start();
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      e.printStackTrace();
    }
  }
  public void runQuarts() throws Exception {
    // 定时任务 ,分组名称信息,分组名 如果不设置分组名 是默认分组Default

    JobDetail jobDetail = new JobDetailImpl("myJobName", "myJobGroupName", QuartsDemo.class);

    // 设置触发器
    SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl("myTiggerName");

    // 触发器 从当前时间开始
    simpleTrigger.setStartTime(new Date());
    // 调用10次
    simpleTrigger.setRepeatCount(10);
    // 每隔2000毫秒 / 2秒
    simpleTrigger.setRepeatInterval(1000);
    // 定义调度
    Scheduler scheudle = new StdSchedulerFactory().getScheduler();
    scheudle.scheduleJob(jobDetail, simpleTrigger);
    // 调度启动
    scheudle.start();
    Thread.currentThread().sleep(10000);
    // 调度关闭
    System.err.println("关闭  ");
    scheudle.shutdown();
  }
示例#27
0
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServletContext ctx = sce.getServletContext();
    StdSchedulerFactory factory = (StdSchedulerFactory) ctx.getAttribute(QUARTZ_FACTORY_KEY);
    try {
      Scheduler scheduler = factory.getScheduler();
      JobDetail jobDetail = JobBuilder.newJob(SchedulerJob.class).build();

      Trigger trigger =
          TriggerBuilder.newTrigger()
              .withIdentity("simple", "group1")
              .startNow()
              .withSchedule(
                  SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever())
              .build();

      scheduler.scheduleJob(jobDetail, trigger);
      scheduler.start();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("There was an error scheduling the job." + e.getMessage());
    }
  }
示例#28
0
  public void run() throws Exception {
    Logger log = LoggerFactory.getLogger(JobStateExample.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 ----------------");

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

    // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds
    JobDetail job1 = newJob(ColorJob.class).withIdentity("job1", "group1").build();

    SimpleTrigger trigger1 =
        newTrigger()
            .withIdentity("trigger1", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4))
            .build();

    // pass initialization parameters into the job
    job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
    job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);

    // schedule the job to run
    Date scheduleTime1 = sched.scheduleJob(job1, trigger1);
    log.info(
        job1.getKey()
            + " will run at: "
            + scheduleTime1
            + " and repeat: "
            + trigger1.getRepeatCount()
            + " times, every "
            + trigger1.getRepeatInterval() / 1000
            + " seconds");

    // job2 will also run 5 times, every 10 seconds
    JobDetail job2 = newJob(ColorJob.class).withIdentity("job2", "group1").build();

    SimpleTrigger trigger2 =
        newTrigger()
            .withIdentity("trigger2", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4))
            .build();

    // pass initialization parameters into the job
    // this job has a different favorite color!
    job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");
    job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);

    // schedule the job to run
    Date scheduleTime2 = sched.scheduleJob(job2, trigger2);
    log.info(
        job2.getKey().toString()
            + " will run at: "
            + scheduleTime2
            + " and repeat: "
            + trigger2.getRepeatCount()
            + " times, every "
            + trigger2.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 -----------------");

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

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

    sched.shutdown(true);

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

    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
  }
示例#29
0
    /**
     * Refreshes the job schedule with the current list of enabled jobs of the type to be scheduled.
     *
     * @param scheduler The scheduler to update.
     * @return The updated scheduler.
     */
    protected Scheduler _refreshJobSchedule(Scheduler scheduler) {
      _disposeScheduler(scheduler);

      String schedulerName = null;
      Properties props = new Properties();

      // Set quartz worker thread properties
      props.put(
          QUARTZ_THREADPOOL_COUNT,
          _configuration.getValue(
              Property.QUARTZ_THREADPOOL_COUNT.getName(),
              Property.QUARTZ_THREADPOOL_COUNT.getDefaultValue()));
      props.put(QUARTZ_THREAD_PRIORITY, QUARTZ_THREAD_PRIORITY_VALUE);
      props.put(
          StdSchedulerFactory
              .PROP_SCHED_SCHEDULER_THREADS_INHERIT_CONTEXT_CLASS_LOADER_OF_INITIALIZING_THREAD,
          true);

      /* Have multiple scheduler instances for different job types, so that when
       * we stop the previous instance of a scheduler during the refresh cycle it does not affect another scheduler.
       */
      switch (Thread.currentThread().getName()) {
        case "schedule-alerts":
        default:
          schedulerName = "AlertScheduler";
      }
      props.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, schedulerName);

      SchedulerFactory schedulerFactory;
      Scheduler result = null;

      try {
        schedulerFactory = new StdSchedulerFactory(props);
        result = schedulerFactory.getScheduler();
      } catch (Exception e) {
        _logger.error("Exception in setting up scheduler: {}", e);
        return result;
      }
      for (CronJob job : getEnabledJobs()) {
        _logger.debug("Adding job to scheduler: {}", job);
        try {
          // Convert from linux cron to quartz cron expression
          String quartzCronEntry =
              "0 " + job.getCronEntry().substring(0, job.getCronEntry().length() - 1) + "?";
          JobDetail jobDetail = JobBuilder.newJob(RunnableJob.class).build();
          CronTrigger cronTrigger =
              TriggerBuilder.newTrigger()
                  .withSchedule(CronScheduleBuilder.cronSchedule(quartzCronEntry))
                  .build();

          // Pass parameter to quartz worker threads
          jobDetail.getJobDataMap().put(RunnableJob.CRON_JOB, job);
          jobDetail.getJobDataMap().put(RunnableJob.LOCK_TYPE, lockType);
          jobDetail.getJobDataMap().put("AlertService", _alertService);
          jobDetail.getJobDataMap().put("AuditService", _auditService);
          result.scheduleJob(jobDetail, cronTrigger);
        } catch (Exception ex) {
          String msg = "Failed to schedule job {0} : {1}";
          JPAEntity entity = JPAEntity.class.cast(job);

          _auditService.createAudit(msg, entity, entity, ex.getMessage());
          _logger.error("Failed to schedule job {} : {}", job, ex.getMessage());
        }
      }
      try {
        result.start();
      } catch (SchedulerException e) {
        _logger.error("Exception in starting scheduler: {}", e);
      }
      _logger.info("Job schedule refreshed.");
      return result;
    }
  /** 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);
    }
  }