@Override
 public void onReceive(final Object message) throws Exception {
   if (message instanceof AskParam) {
     AskParam askParam = (AskParam) message;
     timeout = askParam.timeout;
     caller = sender();
     targetActor = context().actorOf(askParam.props);
     context().watch(targetActor);
     targetActor.forward(askParam.message, context());
     final Scheduler scheduler = context().system().scheduler();
     timeoutMessage =
         scheduler.scheduleOnce(
             askParam.timeout.duration(), self(), new AskTimeout(), context().dispatcher(), null);
   } else if (message instanceof Terminated) {
     sendFailureToCaller(new ActorKilledException("Target actor terminated."));
     timeoutMessage.cancel();
     context().stop(self());
   } else if (message instanceof AskTimeout) {
     sendFailureToCaller(
         new TimeoutException("Target actor timed out after " + timeout.toString()));
     context().stop(self());
   } else {
     unhandled(message);
   }
 }
  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.
    }
  }
Exemplo n.º 3
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");
  }
Exemplo n.º 4
0
  @Test
  public void shoudKillCommandGroupThatUsesRequirementOfAnother() {
    Requirable required =
        new Requirable() {
          @Override
          public String toString() {
            return "R0";
          }
        };
    CommandWithRequirement r0 = new CommandWithRequirement(required, 0, list, true);
    CommandWithRequirement r1 = new CommandWithRequirement(required, 1, list, true);
    CommandWithRequirement r2 = new CommandWithRequirement(required, 2, list, true);
    RequiredGroup g = new RequiredGroup(r0, r1, r2);

    CommandWithRequirement r3 = new CommandWithRequirement(required, 3, list, false);
    scheduler.submit(g);

    scheduler.execute(0);
    assertThat(list).isEqualTo(listOf("R0 init", "R0 exe", "R0 end"));
    list.clear();

    scheduler.submit(r3);
    scheduler.execute(1);
    assertThat(list).isEqualTo(listOf("R1 inter", "R3 init", "R3 exe", "R3 end"));
    list.clear();

    scheduler.execute(2);
    assertThat(list).isEmpty();
  }
Exemplo n.º 5
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);
    }
  }
  @Test
  public void testCorrectness() {
    String costMethod = "MAXLIKELIHOOD";
    NominalProject project = setUpNominalProject();
    ILabelProbabilityDistributionCostCalculator lpdcc =
        LabelProbabilityDistributionCostCalculators.get(costMethod);
    IPriorityCalculator<String> pc = new CostBasedPriorityCalculator(lpdcc);
    Scheduler<String> scheduler = new Scheduler<String>(project, pc);
    Worker worker = new Worker("Worker1");
    INominalData data = project.getData();
    LObject<String> object1 = data.getOrCreateObject("object1");
    LObject<String> object2 = data.getOrCreateObject("object2");
    int w = 0;
    data.addAssign(assign(w++, object1, "A"));
    data.addAssign(assign(w++, object1, "B"));
    data.addAssign(assign(w++, object2, "A"));
    scheduler.update();
    LObject<String> object = scheduler.nextObject();
    assertEquals(object1, object);
    object = scheduler.nextObject();
    assertEquals(object1, object);
    scheduler.update();
    object = scheduler.nextObject();
    assertEquals(object1, object);

    data.addAssign(assign(w++, object2, "B"));
    data.addAssign(assign(w++, object2, "C"));
    scheduler.update();
    assertEquals(object2, scheduler.nextObject());

    data.addAssign(assign(w++, object2, "C"));
    data.addAssign(assign(w++, object2, "C"));
    scheduler.update();
    assertEquals(object1, scheduler.nextObject());
  }
Exemplo n.º 7
0
  public boolean stop() {
    try {
      if (scheduler != null && scheduler.isStarted()) {

        // This is to immediately stop the scheduler to avoid firing new services
        scheduler.standby();

        if (logger.isDebugEnabled()) {
          logger.debug("ShuttingDown Message Processor Scheduler : " + scheduler.getMetaData());
        }

        try {
          scheduler.interrupt(
              new JobKey(
                  name + "-job", MessageProcessorConstants.SCHEDULED_MESSAGE_PROCESSOR_GROUP));
        } catch (UnableToInterruptJobException e) {
          logger.info("Unable to interrupt job [" + name + "-job]");
        }

        // gracefully shutdown
        scheduler.shutdown(true);
      }

    } catch (SchedulerException e) {
      throw new SynapseException("Error ShuttingDown Message processor scheduler ", e);
    }

    if (logger.isDebugEnabled()) {
      logger.debug("Stopped message processor [" + getName() + "].");
    }

    return true;
  }
Exemplo n.º 8
0
  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();
  }
Exemplo n.º 9
0
 @Test
 public void doTest() throws SchedulerException, MeasurementException {
   PollJob job = new PollJob();
   JobExecutionContext context = mock(JobExecutionContext.class);
   Map params = new HashMap();
   JobDataMap jobMap = new JobDataMap(params);
   MeasurementDefinition def = MocksFactory.createMockMeasurementDefinition();
   MeasurementListener listener = mock(MeasurementListener.class);
   Scheduler scheduler = mock(Scheduler.class);
   CoreMeasurementService service = mock(CoreMeasurementService.class);
   SchedulerContext schedulerContext =
       new SchedulerContext(
           Collections.singletonMap(PollJob.MEASUREMENT_SERVICE_ATTR_NAME, service));
   jobMap.put(PollJob.LISTENER_ATTR_NAME, listener);
   jobMap.put(PollJob.MEASUREMENT_DEF_ATTR_NAME, def);
   jobMap.put(PollJob.MEASUREMENT_SERVICE_ATTR_NAME, service);
   when(context.getMergedJobDataMap()).thenReturn(jobMap);
   when(context.getScheduler()).thenReturn(scheduler);
   when(scheduler.getContext()).thenReturn(schedulerContext);
   CapabilityValue capValue = new CapabilityValue(RandomUtils.nextLong());
   when(service.getCapabilityValue(Matchers.<String>any(), Matchers.<String>any()))
       .thenReturn(capValue);
   job.execute(context);
   verify(context).getMergedJobDataMap();
   verify(service).getCapabilityValue(def.getResourceUri(), def.getCapabilityUri());
   verify(listener).newCapabilityValue(capValue);
   assertEquals(capValue.getMetricsId(), def.getId());
 }
Exemplo n.º 10
0
  public boolean activate() {
    try {
      if (scheduler != null && scheduler.isInStandbyMode()) {
        if (logger.isDebugEnabled()) {
          logger.debug("Starting Message Processor Scheduler : " + scheduler.getMetaData());
        }

        scheduler.start();

        if (this.isPaused()) {
          resumeService();
        }

        if (logger.isDebugEnabled()) {
          logger.debug("Successfully re-activated the message processor [" + getName() + "]");
        }

        setActivated(isActive());

        return true;
      } else {
        return false;
      }
    } catch (SchedulerException e) {
      throw new SynapseException("Error Standing-by Message processor scheduler ", e);
    }
  }
Exemplo n.º 11
0
 // private ArrayList<RegistryEntry> readFromRegister(String key, Session session) {
 private String readFromRegister(String key, Session session) {
   // TODO Auto-generated method stub
   // Map<String, String> resultMap = new HashMap<String, String>();
   String CLID = null, STATUS = null;
   String cqlStr = "SELECT * from consistify.registry WHERE key='" + key + "'";
   Statement statement = new SimpleStatement(cqlStr);
   ResultSet results = session.execute(statement);
   CopyOnWriteArrayList<RegistryEntry> rList = new CopyOnWriteArrayList<RegistryEntry>();
   RegistryEntry r = null;
   Scheduler scheduler = new Scheduler();
   for (Row aRow : results) {
     // if (!resultMap.containsKey(aRow.getKey())) {
     if (aRow.getString("CREATETIME") != null && aRow.getString("key").equalsIgnoreCase(key)) {
       r = new RegistryEntry();
       r.setKey(aRow.getString("key"));
       // System.out.println("**222*CLID:=="+aRow.getString("CLID"));
       r.setCLID(aRow.getString("CLID"));
       r.setDEADLINE(aRow.getString("DEADLINE"));
       r.setINDEX(aRow.getString("INDIC"));
       r.setLATENCYDEP(aRow.getString("LATENCYDEP"));
       r.setWAITINGTIME(aRow.getString("WAITINGTIME"));
       r.setSTATUS(aRow.getString("STATUS"));
       r.setCREATETIME(aRow.getString("CREATETIME"));
       rList.add(r);
     }
     // resultMap.put(aRow.getKey(), ++rowCnt);
     // System.out.println(aRow.getKey() + ":" + rowCnt);
     // }
   }
   // CLID = scheduler.schedule(rList).split(":")[0];
   CLID = scheduler.schedule(rList);
   // System.out.println("****CLID:="+CLID);
   return CLID;
 }
Exemplo n.º 12
0
  public void testGranularity() {

    Scheduler s = new Scheduler();

    // This should be fine
    s.setScheduleGranularity(1);

    try {

      // but this is not
      s.setScheduleGranularity(0);

    } catch (IllegalArgumentException ex) {
      assertEquals("Wrong exception message", "0: value doesn't make sense", ex.getMessage());
    }

    long value = -1 * Math.abs(rg.nextLong());

    try {
      // and neither is this
      s.setScheduleGranularity(value);

    } catch (IllegalArgumentException ex) {
      assertEquals(
          "Wrong exception message", value + ": value doesn't make sense", ex.getMessage());
    }
  }
Exemplo n.º 13
0
  public void testFastStart() {

    NDC.push("testFastStart");

    try {

      ScheduleUpdater u =
          new ScheduleUpdater() {

            @Override
            public Map<Thermostat, SortedMap<Period, ZoneStatus>> update() throws IOException {

              // Bad implementation, but shouldn't break anything
              return null;
            }
          };

      Scheduler s = new Scheduler(u);

      s.setScheduleGranularity(50);

      // This instance will run until the JVM is gone or Scheduler#ScheduledExecutorService is
      // otherwise stopped
      s.start(0);

      Thread.sleep(100);

    } catch (InterruptedException ex) {

      throw new IllegalStateException(ex);

    } finally {
      NDC.pop();
    }
  }
Exemplo n.º 14
0
  /**
   * Test of schedule method, immediate execution, blocking in the scheduled task, of class
   * Scheduler.
   */
  @Test
  public void scheduleImmediateBlocking() {
    System.out.println("schedule, immediate, blocking");
    final CountDownLatch barrier = new CountDownLatch(1);
    SchedulerTask task =
        new SchedulerTask() {

          public void onSchedule(long timeStamp) {
            try {
              barrier.countDown();
              Thread.sleep(10000000);
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
            }
          }
        };
    Quantum interval = Quantum.seconds(2000);
    Scheduler instance = Scheduler.sharedInstance();
    ScheduledTask scheduled = instance.schedule(task, interval, true);
    stasks.add(scheduled);
    try {
      boolean executed = barrier.await(1000, TimeUnit.SECONDS);
      assertTrue(executed);
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }
  }
Exemplo n.º 15
0
 /** Print a journal entry */
 public void print(JournalEntry j) {
   try {
     scheduler.enter(j);
     // ...
   } catch (InterruptedException e) {
   } // try
   scheduler.done();
 } // print(JournalEntry)
Exemplo n.º 16
0
 /**
  * Play a sound only once, and allow it only once every interval. Very useful for sounds made
  * while enemies are on stage, since it won't play concurrent sounds.
  *
  * @param sound
  * @param volume
  * @param identifier
  * @param interval
  */
 public static void playSoundSingle(
     final Getter<Sound> getter, float volume, String identifier, long interval) {
   if (!Scheduler.isTracked(identifier, identifier)) {
     Sound sound = getter.get();
     sound.play(volume);
     Scheduler.track(identifier, identifier, interval);
   }
 }
Exemplo n.º 17
0
  /** Test of sharedInstance method, of class Scheduler. */
  @Test
  public void sharedInstance() {
    System.out.println("sharedInstance");

    Scheduler result1 = Scheduler.sharedInstance();
    Scheduler result2 = Scheduler.sharedInstance();
    assertTrue(result1 == result2); // shared instance MUST remain the same across all calls
  }
  @Test
  public void testScheduleWithDyingInstances() {
    try {
      Scheduler scheduler = new Scheduler(TestingUtils.defaultExecutionContext());

      Instance i1 = getRandomInstance(2);
      Instance i2 = getRandomInstance(2);
      Instance i3 = getRandomInstance(1);

      scheduler.newInstanceAvailable(i1);
      scheduler.newInstanceAvailable(i2);
      scheduler.newInstanceAvailable(i3);

      List<SimpleSlot> slots = new ArrayList<SimpleSlot>();
      slots.add(scheduler.allocateSlot(new ScheduledUnit(getDummyTask()), false).get());
      slots.add(scheduler.allocateSlot(new ScheduledUnit(getDummyTask()), false).get());
      slots.add(scheduler.allocateSlot(new ScheduledUnit(getDummyTask()), false).get());
      slots.add(scheduler.allocateSlot(new ScheduledUnit(getDummyTask()), false).get());
      slots.add(scheduler.allocateSlot(new ScheduledUnit(getDummyTask()), false).get());

      i2.markDead();

      for (SimpleSlot slot : slots) {
        if (slot.getOwner() == i2) {
          assertTrue(slot.isCanceled());
        } else {
          assertFalse(slot.isCanceled());
        }

        slot.releaseSlot();
      }

      assertEquals(3, scheduler.getNumberOfAvailableSlots());

      i1.markDead();
      i3.markDead();

      // cannot get another slot, since all instances are dead
      try {
        scheduler.allocateSlot(new ScheduledUnit(getDummyTask()), false).get();
        fail("Scheduler served a slot from a dead instance");
      } catch (NoResourceAvailableException e) {
        // fine
      } catch (Exception e) {
        fail("Wrong exception type.");
      }

      // now the latest, the scheduler should have noticed (through the lazy mechanisms)
      // that all instances have vanished
      assertEquals(0, scheduler.getNumberOfInstancesWithAvailableSlots());
      assertEquals(0, scheduler.getNumberOfAvailableSlots());
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
 void deleteJob(String id) {
   JobKey jobKey = createJobKey(id);
   try {
     if (scheduler.checkExists(jobKey)) {
       scheduler.deleteJob(jobKey);
     }
   } catch (SchedulerException e) {
     throw new BusinessException("更新任务失败", e, 500);
   }
 }
 /**
  * Initializes the QuartzEventScheduler. Makes the configured {@link EventBus} available to the
  * Quartz Scheduler.
  *
  * @throws SchedulerException if an error occurs preparing the Quartz Scheduler for use.
  */
 @PostConstruct
 public void initialize() throws SchedulerException {
   Assert.notNull(scheduler, () -> "A Scheduler must be provided.");
   Assert.notNull(eventBus, () -> "An EventBus must be provided.");
   Assert.notNull(jobDataBinder, () -> "An EventJobDataBinder must be provided.");
   scheduler.getContext().put(FireEventJob.EVENT_BUS_KEY, eventBus);
   scheduler.getContext().put(FireEventJob.TRANSACTION_MANAGER_KEY, transactionManager);
   scheduler.getContext().put(FireEventJob.EVENT_JOB_DATA_BINDER_KEY, jobDataBinder);
   initialized = true;
 }
Exemplo n.º 21
0
  public void scheduleAndQueueTPCC(int index, String key, long l, String clId, long tInv) {
    Scheduler scheduler = new Scheduler();
    // Session session = null;
    String cLevel = "ALL", condn = "price>20";
    ClientQueryExampleThread clientQueryExampleThread = new ClientQueryExampleThread(clId, tInv, 1);
    if (ClientQueryExampleThread.session == null || ClientQueryExampleThread.session.isClosed())
      ClientQueryExampleThread.session =
          ClientQueryExampleThread.callClient(cLevel, condn); // unblock for deploy
    Query q = null;
    // UUID idOne = UUID.randomUUID();
    String CLID = null; // String.valueOf(idOne) + String.valueOf(System.currentTimeMillis());
    long latencyDep = 0;
    l = System.currentTimeMillis() - l;
    // key = (String)
    // ((HashMap<String,String>)DependencyChecker.serializeList.get(index)).keySet().toArray()[0];

    curr_deadline = curr_deadline - (System.currentTimeMillis() - tInv);
    createRegistry(ClientQueryExampleThread.session);

    writeToRegister(
        key,
        index,
        clId,
        l,
        latencyDep,
        curr_deadline,
        "OFF",
        ClientQueryExampleThread.session); // unblock for deploy
    System.out.println(
        "***After write to register"); // for thread "+Thread.currentThread().getName());
    // CLID = readFromRegister(key, session);//unblock for deploy
    // System.out.println("****rlist size:="+ rList.size());
    // if(rList.size()>0)
    // if(CLID!=null)
    // {
    // CLID = scheduler.schedule(rList).split(":")[0];
    // STATUS = scheduler.schedule(rList).split(":")[1];

    while (readFromRegister(key, ClientQueryExampleThread.session) != null
        && readFromRegister(key, ClientQueryExampleThread.session).contains(":")
        && readFromRegister(key, ClientQueryExampleThread.session)
            .split(":")[1]
            .equalsIgnoreCase("OFF")
        && !clId.equalsIgnoreCase(
            readFromRegister(key, ClientQueryExampleThread.session)
                .split(":")[0])) // || !STATUS.equalsIgnoreCase("OFF"))
    {
      // System.out.println("***Client " + clId +"Waiting for the lock to the column "+key);// for
      // thread "+Thread.currentThread().getName());
      // System.out.println("***Waiting for the lock to the column "+key);// for thread
      // "+Thread.currentThread().getName());
    }
    scheduler.requestLock(ClientQueryExampleThread.session, key, clId, index); // unblock for deploy
    System.out.println("***After requesting the lock to the columnfor the query index" + index);
  }
Exemplo n.º 22
0
 @Test
 public void shouldExecuteCommandsTogether() {
   Command c = new SimulCommandGroup();
   scheduler.submit(c);
   scheduler.execute(0);
   // After one step, all three should have run
   assertThat(list)
       .isEqualTo(
           listOf(
               "C0 init", "C0 exe", "C0 fin", "C1 init", "C1 exe", "C1 fin", "C2 init", "C2 exe",
               "C2 fin"));
 }
 /** This method adds the {@link #JOBKEY_DATABASE_UPDATE_INSTANT} job to the scheduler. */
 public void startInstantDatabaseUpdate() {
   try {
     if (!sched.checkExists(JOBKEY_DATABASE_UPDATE_INSTANT)) {
       sched.addJob(instantDatabaseUpdateJob, true);
     }
     if (!QuartzUpdateDatabaseJob.IS_RUNNING) {
       sched.triggerJob(JOBKEY_DATABASE_UPDATE_INSTANT);
     }
   } catch (SchedulerException ex) {
     Logger.getLogger(QuartzSchedulerController.class.getName()).log(Level.SEVERE, null, ex);
     throw new WebApplicationException(PreparedServerResponses.ERROR_SCHEDULER);
   }
 }
Exemplo n.º 24
0
  public boolean deactivate() {
    try {
      if (scheduler != null && scheduler.isStarted()) {
        if (logger.isDebugEnabled()) {
          logger.debug("Deactivating message processor [" + getName() + "]");
        }

        // This is to immediately stop the scheduler to avoid firing new services
        scheduler.standby();

        try {
          scheduler.interrupt(
              new JobKey(
                  name + "-job", MessageProcessorConstants.SCHEDULED_MESSAGE_PROCESSOR_GROUP));
        } catch (UnableToInterruptJobException e) {
          logger.info("Unable to interrupt job [" + name + "-job]");
        }

        // This is to remove the consumer from the queue.
        messageConsumer.cleanup();

        if (logger.isDebugEnabled()) {
          logger.debug("Successfully deactivated the message processor [" + getName() + "]");
        }

        setActivated(isActive());

        // This means the deactivation has happened automatically. So we have to persist the
        // deactivation manually.
        if (isPaused()) {
          try {
            // TODO: Need to make sure if this is the best way.
            String directory = configuration.getPathToConfigFile() + "/message-processors";
            DeploymentEngine deploymentEngine =
                (DeploymentEngine) configuration.getAxisConfiguration().getConfigurator();
            MessageProcessorDeployer dep =
                (MessageProcessorDeployer) deploymentEngine.getDeployer(directory, "xml");
            dep.restoreSynapseArtifact(name);
          } catch (Exception e) {
            logger.warn("Couldn't persist the state of the message processor [" + name + "]");
          }
        }

        return true;
      } else {
        return false;
      }
    } catch (SchedulerException e) {
      throw new SynapseException("Error Standing-by Message processor scheduler ", e);
    }
  }
Exemplo n.º 25
0
  /** Test the no-argument {@link Scheduler#start()} method. */
  public void testStart() {

    NDC.push("testStart");

    try {

      Scheduler s = new Scheduler();

      s.start();

    } finally {
      NDC.pop();
    }
  }
Exemplo n.º 26
0
  @Test
  public void shouldExecuteTwoCommandsTogetherAndOneAfter() {
    Command c = new TwoOneGroup();
    scheduler.submit(c);
    // After one step, first two should have run
    scheduler.execute(0);
    assertThat(list)
        .isEqualTo(listOf("C0 init", "C0 exe", "C0 fin", "C1 init", "C1 exe", "C1 fin"));
    list.clear();

    // After two steps, all three should have run
    scheduler.execute(0);
    assertThat(list).isEqualTo(listOf("C2 init", "C2 exe", "C2 fin"));
  }
  /**
   * This is executed when the flusher is to write all of the data to the underlying socket. In this
   * situation the writes are attempted in a non blocking way, if the task does not complete then
   * this will simply enqueue the writing task for OP_WRITE and leave the method. This returns true
   * if all the buffers are written.
   */
  private synchronized void execute() throws IOException {
    boolean ready = writer.flush();

    if (!ready) {
      boolean block = writer.isBlocking();

      if (!block && !closed) {
        scheduler.release();
      }
      scheduler.repeat();
    } else {
      scheduler.ready();
    }
  }
Exemplo n.º 28
0
  @Test
  public void shoudKillCommandThatUsesRequirementOfAnother() {
    Requirable required = new Requirable() {};
    CommandWithRequirement r0 = new CommandWithRequirement(required, 0, list, true);
    CommandWithRequirement r1 = new CommandWithRequirement(required, 1, list, false);
    CommandWithRequirement r2 = new CommandWithRequirement(required, 2, list, true);

    scheduler.submit(r0);
    scheduler.submit(r1);
    scheduler.submit(r2);

    scheduler.execute(0);
    assertThat(list).isEqualTo(listOf("R0 inter", "R1 init", "R1 exe", "R1 end"));
    list.clear();
  }
Exemplo n.º 29
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);
   }
 }
Exemplo n.º 30
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;
  }