Esempio n. 1
0
 public void testFixedDelayRunnable() throws Exception {
   TestRunnable r = new TestRunnable();
   ScheduledFuture<?> f = schedPooled.scheduleWithFixedDelay(r, 10, 10, TimeUnit.MILLISECONDS);
   assertFalse(f.isDone());
   assertEquals(0, r.runs);
   Thread.sleep(20);
   assertTrue(r.runs > 0);
   assertFalse(f.isCancelled());
   f.cancel(true);
   assertTrue(f.isCancelled());
 }
  public void testIsDone3() throws InterruptedException {
    TimeScheduler.Task task = new DynamicTask(new long[] {-1});
    ScheduledFuture<?> future = timer.scheduleWithDynamicInterval(task);
    Thread.sleep(100);
    assertFalse(future.isCancelled());
    assertTrue(future.isDone());

    boolean success = future.cancel(true);
    if (success) assertTrue(future.isCancelled());
    else assertFalse(future.isCancelled());
    assertTrue(future.isDone());
  }
  public void testIsDone() throws InterruptedException {
    TimeScheduler.Task task = new DynamicTask();
    ScheduledFuture<?> future = timer.scheduleWithDynamicInterval(task);

    assertFalse(future.isCancelled());
    assertFalse(future.isDone());

    Thread.sleep(3000);
    assertFalse(future.isCancelled());
    assertFalse(future.isDone());

    future.cancel(true);
    assertTrue(future.isCancelled());
    assertTrue(future.isDone());
  }
 private void releaseAllocation() {
   if (refreshTask != null && !refreshTask.isCancelled()) {
     logger.debug("Releasing previous allocation");
     sendBlockingStunRequest(MessageFactory.createRefreshRequest(0));
     refreshTask.cancel(true);
   }
 }
  @Test
  public void testFixedDelayPeriodicTaskIsCancelledByShutdown() throws InterruptedException {
    OutOfBandScheduledExecutor scheduler = new OutOfBandScheduledExecutor();
    ExecutorService worker = Executors.newSingleThreadExecutor();
    try {
      PartitionedScheduledExecutor executor = new PartitionedScheduledExecutor(scheduler, worker);

      ScheduledFuture<?> future =
          executor.scheduleWithFixedDelay(
              new Runnable() {

                @Override
                public void run() {
                  Assert.fail("Should not run!");
                }
              },
              2,
              1,
              MINUTES);

      executor.shutdown();
      assertThat(executor.awaitTermination(30, SECONDS), is(true));
      assertThat(executor.isShutdown(), is(true));
      assertThat(executor.isTerminated(), is(true));

      assertThat(future.isCancelled(), is(true));
    } finally {
      worker.shutdown();
    }
  }
 @Override
 public void run() {
   if (future.isCancelled()) {
     return;
   }
   final RequestHolder holder = clientHandlers.remove(requestId);
   if (holder != null) {
     // add it to the timeout information holder, in case we are going to get a response later
     long timeoutTime = System.currentTimeMillis();
     timeoutInfoHandlers.put(
         requestId,
         new TimeoutInfoHolder(holder.node(), holder.action(), sentTime, timeoutTime));
     holder
         .handler()
         .handleException(
             new ReceiveTimeoutTransportException(
                 holder.node(),
                 holder.action(),
                 "request_id ["
                     + requestId
                     + "] timed out after ["
                     + (timeoutTime - sentTime)
                     + "ms]"));
   }
 }
Esempio n. 7
0
    public V2 call() throws Exception {
      try {
        ZimbraLog.scheduler.debug("Executing task %s", mId);
        mLastResult = mTask.call();
        ZimbraLog.scheduler.debug("Task returned result %s", mLastResult);

        if (mCallbacks != null) {
          for (ScheduledTaskCallback<V2> callback : mCallbacks) {
            callback.afterTaskRun(mTask, mLastResult);
          }
        }
      } catch (Throwable t) {
        if (t instanceof OutOfMemoryError) {
          ZimbraLog.scheduler.fatal("Shutting down", t);
          System.exit(1);
        }
        ZimbraLog.scheduler.warn("Exception during execution of task %s", mId, t);
        mLastResult = null;
      }

      boolean cancelled = false;
      if (mSchedule != null) {
        // mSchedule may have not been set by schedule() if the task runs immediately
        cancelled = mSchedule.isCancelled();
      }

      // Reschedule if this is a recurring task
      if (mRecurs && !cancelled) {
        ZimbraLog.scheduler.debug("Rescheduling task %s", mId);
        mSchedule = mThreadPool.schedule(this, mIntervalMillis, TimeUnit.MILLISECONDS);
      } else {
        ZimbraLog.scheduler.debug("Not rescheduling task %s.  mRecurs=%b", mId, mRecurs);
      }
      return mLastResult;
    }
Esempio n. 8
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testStopMonitoringWhenFutureIsNotComplete() {
    ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class);
    expect(mockFuture.isCancelled()).andReturn(false);
    expect(mockFuture.isDone()).andReturn(false);
    expect(mockFuture.cancel(false)).andReturn(true);

    ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class);
    expect(
            schedulerMock.scheduleWithFixedDelay(
                anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class)))
        .andReturn(mockFuture);

    replay(mockFuture);
    replay(schedulerMock);

    AsyncMonitor<Object> monitor =
        mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), new EventBus());

    assertNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.startMonitoring(null);
    assertNotNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.stopMonitoring();

    verify(mockFuture);
    verify(schedulerMock);
  }
Esempio n. 9
0
  public void unschedule(long taskId, DeadlineType type) {
    List<ScheduledFuture<ScheduledTaskDeadline>> knownFutures = null;
    if (type == DeadlineType.START) {
      knownFutures = this.startScheduledTaskDeadlines.get(taskId);
    } else if (type == DeadlineType.END) {
      knownFutures = this.endScheduledTaskDeadlines.get(taskId);
    }
    if (knownFutures == null) {
      return;
    }
    Iterator<ScheduledFuture<ScheduledTaskDeadline>> it = knownFutures.iterator();
    while (it.hasNext()) {
      ScheduledFuture<ScheduledTaskDeadline> scheduled = it.next();
      try {
        if (!scheduled.isDone() && !scheduled.isCancelled()) {
          scheduled.cancel(true);
        }

      } catch (Exception e) {
        logger.log(
            Level.SEVERE,
            " XXX :Error while cancelling scheduled deadline task for Task with id "
                + taskId
                + " -> "
                + e);
      }
    }
  }
  public void stop() {
    try {
      lock.lock();

      if (networkJob != null && !networkJob.isCancelled()) {
        networkJob.cancel(true);
        networkJob = null;
      }

      try {
        if (selector != null) {

          selector.wakeup();

          boolean isContinue = true;
          while (isContinue) {
            try {
              for (SelectionKey selectionKey : selector.keys()) {
                selectionKey.channel().close();
                selectionKey.cancel();
              }
              isContinue = false; // continue till all keys are cancelled
            } catch (ConcurrentModificationException e) {
              logger.warn(
                  "An exception occurred while closing a selector key : '{}'", e.getMessage());
            }
          }

          selector.close();
        }
      } catch (IOException e) {
        logger.warn("An exception occurred while closing the selector : '{}'", e.getMessage());
      }

      if (broadcastKey != null) {
        try {
          broadcastKey.channel().close();
        } catch (IOException e) {
          logger.warn(
              "An exception occurred while closing the broadcast channel : '{}'", e.getMessage());
        }
      }

      if (unicastKey != null) {
        try {
          unicastKey.channel().close();
        } catch (IOException e) {
          logger.warn(
              "An exception occurred while closing the unicast channel : '{}'", e.getMessage());
        }
      }

      ipAddress = null;
    } finally {
      lock.unlock();
    }
  }
  public void testDynamicTaskCancel() throws InterruptedException {

    TimeScheduler.Task task = new DynamicTask();
    ScheduledFuture<?> future = timer.scheduleWithDynamicInterval(task);

    assertFalse(future.isCancelled());
    assertFalse(future.isDone());

    Thread.sleep(3000);
    assertFalse(future.isCancelled());
    assertFalse(future.isDone());

    boolean success = future.cancel(true);
    assertTrue(success);
    assertTrue(future.isCancelled());
    assertTrue(future.isDone());

    success = future.cancel(true);
    assertTrue(success); // we try to cancel an already cancelled task
  }
Esempio n. 12
0
  @Override
  public void dispose() {

    logger.trace("Disposing the Tesla handler for {}", getThing().getUID());

    if (eventJob != null && !eventJob.isCancelled()) {
      eventJob.cancel(true);
      eventJob = null;
    }

    if (fastStateJob != null && !fastStateJob.isCancelled()) {
      fastStateJob.cancel(true);
      fastStateJob = null;
    }

    if (slowStateJob != null && !slowStateJob.isCancelled()) {
      slowStateJob.cancel(true);
      slowStateJob = null;
    }
  }
 @Override
 public void run() {
   if (future != null && future.isCancelled()) {
     return;
   }
   if (lifecycle.stoppedOrClosed()) {
     listener.onClose();
   } else {
     listener.onTimeout(this.timeout);
   }
   // note, we rely on the listener to remove itself in case of timeout if needed
 }
Esempio n. 14
0
  @Override
  public void initialize() {

    logger.trace("Initializing the Tesla handler for {}", getThing().getUID());

    connect();

    if (getThing().getStatus() == ThingStatus.ONLINE) {

      if (eventJob == null || eventJob.isCancelled()) {
        eventJob =
            scheduler.scheduleAtFixedRate(
                eventRunnable, 0, EVENT_REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
      }

      Map<Object, Rate> channels = new HashMap<Object, Rate>();
      channels.put(TESLA_DATA_THROTTLE, new Rate(10, 10, TimeUnit.SECONDS));
      channels.put(TESLA_COMMAND_THROTTLE, new Rate(20, 1, TimeUnit.MINUTES));

      Rate firstRate = new Rate(20, 1, TimeUnit.MINUTES);
      Rate secondRate = new Rate(200, 10, TimeUnit.MINUTES);
      stateThrottler = new QueueChannelThrottler(firstRate, scheduler, channels);
      stateThrottler.addRate(secondRate);

      if (fastStateJob == null || fastStateJob.isCancelled()) {
        fastStateJob =
            scheduler.scheduleWithFixedDelay(
                fastStateRunnable, 0, FAST_STATUS_REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
      }

      if (slowStateJob == null || slowStateJob.isCancelled()) {
        slowStateJob =
            scheduler.scheduleWithFixedDelay(
                slowStateRunnable, 0, SLOW_STATUS_REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
      }
    }
  }
  @Override
  public void dispose() {

    // stop our duration counter
    if (timeCounterJob != null && !timeCounterJob.isCancelled()) {
      timeCounterJob.cancel(true);
      timeCounterJob = null;
    }

    if (squeezeBoxServerHandler != null) {
      squeezeBoxServerHandler.removePlayerCache(mac);
    }
    logger.debug("Thing {} disposed.", getThing().getUID());
    super.dispose();
  }
Esempio n. 16
0
  @Override
  public synchronized void start() {
    logger.debug("start pollingScheduler");
    if (pollingScheduler == null || pollingScheduler.isCancelled()) {
      pollingScheduler =
          scheduler.scheduleAtFixedRate(
              new PollingRunnable(), 0, config.getPollingFrequency(), TimeUnit.MILLISECONDS);
      sceneMan.start();
    }
    if (sceneJobExecutor != null) {
      this.sceneJobExecutor.startExecutor();
    }

    if (sensorJobExecutor != null) {
      this.sensorJobExecutor.startExecutor();
    }
  }
Esempio n. 17
0
  /**
   * Send the commands to restore the original settings for mode & temperature to end the automatic
   * update cycle
   */
  private synchronized void refreshActualsRestore() {
    try {
      refreshingActuals = false;
      if (originalMode == ThermostatModeType.AUTOMATIC
          || originalMode == ThermostatModeType.MANUAL) {
        logger.debug("Finished Actuals Refresh: Restoring Temp {}", originalSetTemp);
        handleCommand(new ChannelUID(getThing().getUID(), CHANNEL_SETTEMP), originalSetTemp);
      }

      if (refreshActualsJob != null && !refreshActualsJob.isCancelled()) {
        refreshActualsJob.cancel(true);
        refreshActualsJob = null;
      }
    } catch (Exception e) {
      logger.debug("Exception occurred during Actuals Refresh : {}", e.getMessage(), e);
    }
  }
  private void initializeAndScheduleCollector(final ConfigManager manager) {
    if (collectionHandler != null && !collectionHandler.isCancelled())
      collectionHandler.cancel(false);

    // set up synchronizer
    final DBAndSchemaSynchronizer synchronizer;
    try {
      synchronizer = DBAndSchemaSynchronizer.getSynchronizer(manager.getCurrentConnectionInfo());
    } catch (IOException e) {
      ErrorHandler.handleError(
          "Error initializing Database Synchronizer",
          e,
          AlarmHandler.TrendExportAlarm.CollectionFailure);
      return;
    }

    // where injection of changing the configuration happens
    TIME_DETERMINATOR.set(
        TimeDeterminator.createTimeDeterminator(manager.getConfiguration().getCollectionString()));
    final TimeDeterminator timeDeterminator = TIME_DETERMINATOR.get();
    timeDeterminator.calculateNextScheduledCollection();
    final long initialDelay = timeDeterminator.calculateInitialDelay();
    final long interval = timeDeterminator.calculateInterval();

    collectionHandler =
        executor.scheduleAtFixedRate(
            new Runnable() {
              @Override
              public void run() {
                try {
                  synchronizer.connect();
                } catch (DatabaseException e) {
                  ErrorHandler.handleError("Database Failure?", e);
                }

                Collection<TrendPathAndDBTableName> trendPathAndDBTableNames =
                    synchronizer.getSourceMappings().getSourcesAndTableNames();
                DataCollector.collectData(
                    synchronizer, synchronizer.getReferencePaths(trendPathAndDBTableNames));
                timeDeterminator.calculateNextScheduledCollection();
              }
            },
            initialDelay,
            interval,
            TimeUnit.MILLISECONDS);
  }
Esempio n. 19
0
 @Override
 public synchronized void stop() {
   logger.debug("stop pollingScheduler");
   if (sceneMan != null) {
     sceneMan.stop();
   }
   if (pollingScheduler != null && !pollingScheduler.isCancelled()) {
     pollingScheduler.cancel(true);
     pollingScheduler = null;
     stateChanged(ManagerStates.STOPPED);
   }
   if (sceneJobExecutor != null) {
     this.sceneJobExecutor.shutdown();
   }
   if (sensorJobExecutor != null) {
     this.sensorJobExecutor.shutdown();
   }
 }
Esempio n. 20
0
 /*
  * (non-Javadoc)
  *
  * @see org.eclipse.smarthome.core.thing.binding.BaseThingHandler#dispose()
  */
 @Override
 public void dispose() {
   logger.debug("Disposing MAX! device {} {}.", getThing().getUID(), maxDeviceSerial);
   if (refreshingActuals) {
     refreshActualsRestore();
   }
   if (refreshActualsJob != null && !refreshActualsJob.isCancelled()) {
     refreshActualsJob.cancel(true);
     refreshActualsJob = null;
   }
   if (bridgeHandler != null) {
     logger.trace("Clear MAX! device {} {} from bridge.", getThing().getUID(), maxDeviceSerial);
     bridgeHandler.clearDeviceList();
     bridgeHandler.unregisterDeviceStatusListener(this);
     bridgeHandler = null;
   }
   updateStatus(ThingStatus.OFFLINE);
   logger.debug("Disposed MAX! device {} {}.", getThing().getUID(), maxDeviceSerial);
   super.dispose();
 }
Esempio n. 21
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testMonitorAndContinueWithtTimeout() throws InterruptedException {
    ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class);
    expect(mockFuture.isCancelled()).andReturn(true);

    ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class);
    expect(
            schedulerMock.scheduleWithFixedDelay(
                anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class)))
        .andReturn(mockFuture);

    replay(mockFuture);
    replay(schedulerMock);

    CoutingEventHandler handler = new CoutingEventHandler();
    EventBus eventBus = new EventBus();
    eventBus.register(handler);

    AsyncMonitor<Object> monitor =
        mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.CONTINUE), eventBus);

    assertNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.startMonitoring(1L);
    assertNotNull(monitor.getFuture());
    assertNotNull(monitor.getTimeout());

    Thread.sleep(2L);
    monitor.run();
    assertEquals(handler.numCompletes, 0);
    assertEquals(handler.numFailures, 0);
    assertEquals(handler.numTimeouts, 1);

    verify(mockFuture);
    verify(schedulerMock);
  }
Esempio n. 22
0
 private void scheduleStartupRules() {
   if (startupJob == null || startupJob.isCancelled() || startupJob.isDone()) {
     startupJob = scheduler.schedule(startupRunnable, 5, TimeUnit.SECONDS);
   }
 }
Esempio n. 23
0
 public void cancelFuture() {
   if (mFuture != null && !mFuture.isCancelled()) {
     mFuture.cancel(true);
     mFuture = null;
   }
 }
Esempio n. 24
0
  private void refreshActualCheck(HeatingThermostat device) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    if (device.getActualTempLastUpdated() == null) {
      Calendar t = Calendar.getInstance();
      t.add(Calendar.MINUTE, REFRESH_ACTUAL_MIN_RATE * -1);
      device.setActualTempLastUpdated(t.getTime());
      logger.info(
          "Actual date reset for {} {} ({}) id: {}",
          device.getType(),
          device.getName(),
          device.getSerialNumber(),
          getThing().getUID());
    }
    long timediff =
        Calendar.getInstance().getTime().getTime() - device.getActualTempLastUpdated().getTime();
    if (timediff > (refreshActualRate * 1000 * 60)) {
      if (!refreshingActuals) {

        logger.debug(
            "Actual needs updating for {} {} ({}) id: {}",
            device.getType(),
            device.getName(),
            device.getSerialNumber(),
            getThing().getUID());

        originalSetTemp = device.getTemperatureSetpoint();
        originalMode = device.getMode();

        if (originalMode == ThermostatModeType.MANUAL
            || originalMode == ThermostatModeType.AUTOMATIC) {
          BigDecimal temporaryTemp = originalSetTemp.toBigDecimal().add(BigDecimal.valueOf(0.5));
          logger.debug("Actuals Refresh: Setting Temp {}", temporaryTemp);
          handleCommand(
              new ChannelUID(getThing().getUID(), CHANNEL_SETTEMP), new DecimalType(temporaryTemp));
          refreshingActuals = true;
        } else {
          logger.debug("Defer Actuals refresh. Only manual refresh for mode AUTOMATIC & MANUAL");
          device.setActualTempLastUpdated(Calendar.getInstance().getTime());
        }

        if (refreshingActuals) {
          updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, "Updating Actual Temperature");

          if (refreshActualsJob == null || refreshActualsJob.isCancelled()) {
            refreshActualsJob =
                scheduler.schedule(
                    refreshActualsRestoreRunnable, REFRESH_ACTUAL_DURATION, TimeUnit.SECONDS);
          }

          device.setActualTempLastUpdated(Calendar.getInstance().getTime());
        }
      }
      logger.debug(
          "Actual Refresh in progress for {} {} ({}) id: {}",
          device.getType(),
          device.getName(),
          device.getSerialNumber(),
          getThing().getUID());
    } else {
      logger.trace(
          "Actual date for {} {} ({}) : {}",
          device.getType(),
          device.getName(),
          device.getSerialNumber(),
          dateFormat.format(device.getActualTempLastUpdated().getTime()));
    }
  }
Esempio n. 25
0
 public synchronized boolean isPaused() {
   return !executor.isShutdown() && (ticker == null || ticker.isCancelled());
 }
Esempio n. 26
0
 public void onEvent() {
   if (future != null && !future.isDone() && !future.isCancelled()) {
     future.cancel(true);
   }
   future = scheduler.schedule(runnable, groupEventsTimeout, TimeUnit.MILLISECONDS);
 }
 @Override
 public boolean isCancelled() {
   return scheduledFuture.isCancelled();
 }
  public void start() {
    try {

      lock.lock();

      logger.debug("Starting LIFX communication handler for bulb '{}'.", macAsHex);

      if (networkJob == null || networkJob.isCancelled()) {
        networkJob =
            scheduler.scheduleWithFixedDelay(
                networkRunnable, 0, PACKET_INTERVAL, TimeUnit.MILLISECONDS);
      }

      source = UUID.randomUUID().getLeastSignificantBits() & (-1L >>> 32);
      logger.debug(
          "The LIFX handler will use '{}' as source identifier", Long.toString(source, 16));
      broadcastAddresses = new ArrayList<InetSocketAddress>();
      interfaceAddresses = new ArrayList<InetAddress>();

      Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
      while (networkInterfaces.hasMoreElements()) {
        NetworkInterface iface = networkInterfaces.nextElement();
        if (iface.isUp() && !iface.isLoopback()) {
          for (InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) {
            if (ifaceAddr.getAddress() instanceof Inet4Address) {
              logger.debug(
                  "Adding '{}' as interface address with MTU {}",
                  ifaceAddr.getAddress(),
                  iface.getMTU());
              if (iface.getMTU() > bufferSize) {
                bufferSize = iface.getMTU();
              }
              interfaceAddresses.add(ifaceAddr.getAddress());
              if (ifaceAddr.getBroadcast() != null) {
                logger.debug("Adding '{}' as broadcast address", ifaceAddr.getBroadcast());
                broadcastAddresses.add(
                    new InetSocketAddress(ifaceAddr.getBroadcast(), BROADCAST_PORT));
              }
            }
          }
        }
      }

      selector = Selector.open();

      DatagramChannel broadcastChannel =
          DatagramChannel.open(StandardProtocolFamily.INET)
              .setOption(StandardSocketOptions.SO_REUSEADDR, true)
              .setOption(StandardSocketOptions.SO_BROADCAST, true);
      broadcastChannel.configureBlocking(false);

      int offset = lightCounter.getAndIncrement();
      logger.debug("Binding the broadcast channel on port {}", BROADCAST_PORT + offset);
      broadcastChannel.bind(new InetSocketAddress(BROADCAST_PORT + offset));

      broadcastKey =
          broadcastChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

      currentLightState.setOffline();

      // look for lights on the network
      GetServiceRequest packet = new GetServiceRequest();
      broadcastPacket(packet);

    } catch (Exception ex) {
      logger.error("Error occured while initializing LIFX handler: " + ex.getMessage(), ex);
    } finally {
      lock.unlock();
    }
  }
Esempio n. 29
0
 public synchronized boolean isRunning() {
   return !executor.isShutdown() && ticker != null && !ticker.isCancelled();
 }
Esempio n. 30
0
 public boolean isEnabled() {
   return !scheduledGossipTask.isCancelled();
 }