com.google.common.util.concurrent.ListenableScheduledFuture Java Examples

The following examples show how to use com.google.common.util.concurrent.ListenableScheduledFuture. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PurgeSchedulingService.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
public synchronized void start(Runnable task) {
    if (isStarted()) {
        return;
    }
    requireNonNull(task, "task");
    final ListeningScheduledExecutorService scheduler = MoreExecutors.listeningDecorator(purgeWorker);
    this.scheduler = scheduler;
    @SuppressWarnings("UnstableApiUsage")
    final ListenableScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(
            task,
            TICK.getSeconds(), TICK.getSeconds(), TimeUnit.SECONDS);

    Futures.addCallback(future, new FutureCallback<Object>() {
        @Override
        public void onSuccess(@Nullable Object result) {}

        @Override
        public void onFailure(Throwable cause) {
            logger.error("Storage purge scheduler stopped due to an unexpected exception:", cause);
        }
    }, purgeWorker);
}
 
Example #2
Source File: WebExperimentSyncer.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void scheduleNextRefresh(boolean refreshWasSuccessful) {
  int delayInMinutes =
      refreshWasSuccessful ? SUCESSFUL_DOWNLOAD_DELAY_MINUTES : DOWNLOAD_FAILURE_DELAY_MINUTES;
  ListenableScheduledFuture<String> refreshResults =
      executor.schedule(new WebExperimentsDownloader(), delayInMinutes, TimeUnit.MINUTES);
  refreshResults.addListener(
      new WebExperimentsResultProcessor(refreshResults), MoreExecutors.directExecutor());
}
 
Example #3
Source File: StatsSender.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
@NotNull
private ListenableScheduledFuture<?> scheduleSend(Services services, String olvVersion, Map<String, Long> stats, String uuid, String javaVersion) {
  return services
    .getTaskSchedulerService()
    .getListeningScheduledExecutorService()
    .schedule(() -> {
      send(services, olvVersion, stats, uuid, javaVersion);
    }, 2L, TimeUnit.SECONDS);
}
 
Example #4
Source File: JumpToCodeSelectionListener.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
@Override
public void valueChanged(ListSelectionEvent e) {
  boolean hasFocus = otrosApplication.getApplicationJFrame().isFocused();
  final boolean enabled = otrosApplication.getConfiguration().getBoolean(ConfKeys.JUMP_TO_CODE_AUTO_JUMP_ENABLED, false);
  if (hasFocus && enabled && !e.getValueIsAdjusting()) {
    try {
      final LogData logData = dataTableModel.getLogData(table.convertRowIndexToModel(e.getFirstIndex()));
      Optional<Integer> line = Optional.empty();
      if (StringUtils.isNotBlank(logData.getLine()) && StringUtils.isAlphanumeric(logData.getLine())) {
        line = Optional.of(Integer.valueOf(logData.getLine()));
      }
      final LocationInfo li = new LocationInfo(
        Optional.ofNullable(logData.getClazz()).orElseGet(logData::getLoggerName),
        logData.getMethod(), logData.getFile(),
        line,
        Optional.ofNullable(logData.getMessage()));
      final JumpToCodeService jumpToCodeService = otrosApplication.getServices().getJumpToCodeService();
      final boolean ideAvailable = jumpToCodeService.isIdeAvailable();
      if (ideAvailable) {
        scheduledJump.map(input -> {
          input.cancel(false);
          return Boolean.TRUE;
        });
        ListeningScheduledExecutorService scheduledExecutorService = otrosApplication.getServices().getTaskSchedulerService().getListeningScheduledExecutorService();
        delayMs = 300;
        ListenableScheduledFuture<?> jump = scheduledExecutorService.schedule(
          new JumpRunnable(li, jumpToCodeService), delayMs, TimeUnit.MILLISECONDS
        );

        scheduledJump = Optional.of(jump);
      }
    } catch (Exception e1) {
      LOGGER.warn("Can't perform jump to code: " + e1.getMessage(), e1);
      e1.printStackTrace();
    }

  }
}
 
Example #5
Source File: DslTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigWithDslNotReadyImmediately() throws Exception {
    final ConfigKey<String> configKey = ConfigKeys.newStringConfigKey("testConfig");
    BrooklynDslDeferredSupplier<?> dsl = BrooklynDslCommon.config(configKey.getName());
    Function<Entity, ConfigValuePair> valueSupplier = new Function<Entity, ConfigValuePair>() {
        private ListenableScheduledFuture<?> future;
        @Override
        public ConfigValuePair apply(final Entity entity) {
            try {
                // If executed in a loop, then wait for previous call's future to complete.
                // If previous assertion used getImmediately, then it won't have waited for the future to complete.
                if (future != null) {
                    future.get(Asserts.DEFAULT_LONG_TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
                    future = null;
                }

                // Reset sensor - otherwise if run in a loop the old value will be picked up, before our execute sets the new value
                entity.sensors().set(TestApplication.MY_ATTRIBUTE, null);
                
                final String expectedValue = Identifiers.makeRandomId(10);
                Runnable job = new Runnable() {
                    @Override
                    public void run() {
                        entity.sensors().set(TestApplication.MY_ATTRIBUTE, expectedValue);
                    }
                };
                future = executor.schedule(job, random.nextInt(20), TimeUnit.MILLISECONDS);

                BrooklynDslDeferredSupplier<?> attributeDsl = BrooklynDslCommon.attributeWhenReady(TestApplication.MY_ATTRIBUTE.getName());
                return new ConfigValuePair(attributeDsl, expectedValue);

            } catch (Exception e) {
                throw Exceptions.propagate(e);
            }
        }
    };
    new ConfigTestWorker(app, configKey, valueSupplier, dsl).satisfiedAsynchronously(true).resolverIterations(2).run();
}
 
Example #6
Source File: PublishingReleaseStatus.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<?> work() {
    int publishingBatchNum = statusInfo.getFinishedBatchNum() + 1;
    final List<Host> machines = statusInfo.getBatches().get(publishingBatchNum);
    preparePush(machines);
    ListenableFuture<?> f1 = executor.submit(new Runnable() {
        @Override
        public void run() {
            push(machines);
        }
    });

    ListenableScheduledFuture<?> f2 = executor.schedule(new Runnable() {
        @Override
        public void run() {
            push(machines);
        }
    }, DELAY_TIME_MS, TimeUnit.MILLISECONDS);

    ListenableFuture<List<Object>> workFuture = Futures.successfulAsList(f1, f2);
    workFuture.addListener(new Runnable() {
        @Override
        public void run() {
            accept(Command.next);
        }
    }, Constants.CURRENT_EXECUTOR);
    return workFuture;
}
 
Example #7
Source File: MDCPropagatingScheduledExecutorService.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
  ListenableFutureTask<Void> task = ListenableFutureTask.create(new MDCPropagatingRunnable(command), null);
  ScheduledFuture<?> scheduled = executorService.schedule(task, delay, unit);
  return new ListenableScheduledTask<>(task, scheduled);
}
 
Example #8
Source File: XdsTestClient.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void runQps() throws InterruptedException, ExecutionException {
  final SettableFuture<Void> failure = SettableFuture.create();
  final class PeriodicRpc implements Runnable {

    @Override
    public void run() {
      final long requestId;
      final Set<XdsStatsWatcher> savedWatchers = new HashSet<>();
      synchronized (lock) {
        currentRequestId += 1;
        requestId = currentRequestId;
        savedWatchers.addAll(watchers);
      }

      SimpleRequest request = SimpleRequest.newBuilder().setFillServerId(true).build();
      ManagedChannel channel = channels.get((int) (requestId % channels.size()));
      final ClientCall<SimpleRequest, SimpleResponse> call =
          channel.newCall(
              TestServiceGrpc.getUnaryCallMethod(),
              CallOptions.DEFAULT.withDeadlineAfter(rpcTimeoutSec, TimeUnit.SECONDS));
      call.start(
          new ClientCall.Listener<SimpleResponse>() {
            private String hostname;

            @Override
            public void onMessage(SimpleResponse response) {
              hostname = response.getHostname();
              // TODO(ericgribkoff) Currently some test environments cannot access the stats RPC
              // service and rely on parsing stdout.
              if (printResponse) {
                System.out.println(
                    "Greeting: Hello world, this is "
                        + hostname
                        + ", from "
                        + call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR));
              }
            }

            @Override
            public void onClose(Status status, Metadata trailers) {
              if (printResponse && !status.isOk()) {
                logger.log(Level.WARNING, "Greeting RPC failed with status {0}", status);
              }
              for (XdsStatsWatcher watcher : savedWatchers) {
                watcher.rpcCompleted(requestId, hostname);
              }
            }
          },
          new Metadata());

      call.sendMessage(request);
      call.request(1);
      call.halfClose();
    }
  }

  long nanosPerQuery = TimeUnit.SECONDS.toNanos(1) / qps;
  ListenableScheduledFuture<?> future =
      exec.scheduleAtFixedRate(new PeriodicRpc(), 0, nanosPerQuery, TimeUnit.NANOSECONDS);

  Futures.addCallback(
      future,
      new FutureCallback<Object>() {

        @Override
        public void onFailure(Throwable t) {
          failure.setException(t);
        }

        @Override
        public void onSuccess(Object o) {}
      },
      MoreExecutors.directExecutor());

  failure.get();
}
 
Example #9
Source File: TestUtils.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableScheduledFuture<?> scheduleWithFixedDelay(
    Runnable runnable, long l, long l1, TimeUnit timeUnit) {
  return delegate.scheduleWithFixedDelay(runnable, 0, 0, timeUnit);
}
 
Example #10
Source File: TestUtils.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableScheduledFuture<?> scheduleAtFixedRate(
    Runnable runnable, long l, long l1, TimeUnit timeUnit) {
  return delegate.scheduleAtFixedRate(runnable, 0, 0, timeUnit);
}
 
Example #11
Source File: TestUtils.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public <V> ListenableScheduledFuture<V> schedule(
    Callable<V> callable, long l, TimeUnit timeUnit) {
  return delegate.schedule(callable, 0, timeUnit);
}
 
Example #12
Source File: TestUtils.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableScheduledFuture<?> schedule(Runnable runnable, long l, TimeUnit timeUnit) {
  return delegate.schedule(runnable, 0, timeUnit);
}
 
Example #13
Source File: MDCPropagatingScheduledExecutorService.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
  NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(new MDCPropagatingRunnable(command));
  ScheduledFuture<?> scheduled = executorService.scheduleWithFixedDelay(task, initialDelay, delay, unit);
  return new ListenableScheduledTask<>(task, scheduled);
}
 
Example #14
Source File: MDCPropagatingScheduledExecutorService.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
  NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(new MDCPropagatingRunnable(command));
  ScheduledFuture<?> scheduled = executorService.scheduleAtFixedRate(task, initialDelay, period, unit);
  return new ListenableScheduledTask<>(task, scheduled);
}
 
Example #15
Source File: MDCPropagatingScheduledExecutorService.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public <V> ListenableScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
  ListenableFutureTask<V> task = ListenableFutureTask.create(new MDCPropagatingCallable<>(callable));
  ScheduledFuture<?> scheduled = executorService.schedule(task, delay, unit);
  return new ListenableScheduledTask<>(task, scheduled);
}
 
Example #16
Source File: CompletableAsync.java    From helloiot with GNU General Public License v3.0 4 votes vote down vote up
public static ListenableScheduledFuture<?> scheduleTask(long millis, long period, Runnable r) {
    return service.scheduleAtFixedRate(r, millis, period, TimeUnit.MILLISECONDS);
}
 
Example #17
Source File: CompletableAsync.java    From helloiot with GNU General Public License v3.0 4 votes vote down vote up
public static ListenableScheduledFuture<?> scheduleTask(long millis, Runnable r) {
    return service.schedule(r, millis, TimeUnit.MILLISECONDS);
}
 
Example #18
Source File: DefaultMirroringService.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
public synchronized void start(CommandExecutor commandExecutor) {
    if (isStarted()) {
        return;
    }

    this.commandExecutor = requireNonNull(commandExecutor, "commandExecutor");

    scheduler = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor(
            new DefaultThreadFactory("mirroring-scheduler", true)));

    // Use SynchronousQueue to prevent the work queue from growing infinitely
    // when the workers cannot handle the mirroring tasks fast enough.
    final SynchronousQueue<Runnable> workQueue = new SynchronousQueue<>();
    worker = MoreExecutors.listeningDecorator(new ThreadPoolExecutor(
            0, numThreads, 90, TimeUnit.SECONDS, workQueue,
            new DefaultThreadFactory("mirroring-worker", true),
            (rejectedTask, executor) -> {
                // We do not want the mirroring tasks to be rejected.
                // Just wait until a worker thread takes it.
                try {
                    workQueue.put(rejectedTask);
                } catch (InterruptedException e) {
                    // Propagate the interrupt to the scheduler.
                    Thread.currentThread().interrupt();
                }
            }));

    final ListenableScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(
            this::schedulePendingMirrors,
            TICK.getSeconds(), TICK.getSeconds(), TimeUnit.SECONDS);

    Futures.addCallback(future, new FutureCallback<Object>() {
        @Override
        public void onSuccess(@Nullable Object result) {}

        @Override
        public void onFailure(Throwable cause) {
            logger.error("Git-to-CD mirroring scheduler stopped due to an unexpected exception:", cause);
        }
    }, MoreExecutors.directExecutor());
}