Tabnine Logo
Duration
Code IndexAdd Tabnine to your IDE (free)

How to use
Duration
in
org.threeten.bp

Best Java code snippets using org.threeten.bp.Duration (Showing top 20 results out of 540)

Refine searchRefine arrow

  • RetrySettings.Builder
  • RetrySettings
origin: googleapis/google-cloud-java

private static RetrySettings retrySettings() {
 return RetrySettings.newBuilder()
   .setMaxRetryDelay(Duration.ofMillis(30000L))
   .setTotalTimeout(Duration.ofMillis(120000L))
   .setInitialRetryDelay(Duration.ofMillis(250L))
   .setRetryDelayMultiplier(1.0)
   .setInitialRpcTimeout(Duration.ofMillis(120000L))
   .setRpcTimeoutMultiplier(1.0)
   .setMaxRpcTimeout(Duration.ofMillis(120000L))
   .build();
}
origin: googleapis/google-cloud-java

public Publisher getPublisherWithCustomRetrySettings(ProjectTopicName topicName)
  throws Exception {
 // [START pubsub_publisher_retry_settings]
 // Retry settings control how the publisher handles retryable failures
 Duration retryDelay = Duration.ofMillis(100); // default : 1 ms
 double retryDelayMultiplier = 2.0; // back off for repeated failures
 Duration maxRetryDelay = Duration.ofSeconds(5); // default : 10 seconds
 Duration totalTimeout = Duration.ofSeconds(1); // default: 0
 Duration initialRpcTimeout = Duration.ofSeconds(1); // default: 0
 Duration maxRpcTimeout = Duration.ofSeconds(10); // default: 0
 RetrySettings retrySettings =
   RetrySettings.newBuilder()
     .setInitialRetryDelay(retryDelay)
     .setRetryDelayMultiplier(retryDelayMultiplier)
     .setMaxRetryDelay(maxRetryDelay)
     .setTotalTimeout(totalTimeout)
     .setInitialRpcTimeout(initialRpcTimeout)
     .setMaxRpcTimeout(maxRpcTimeout)
     .build();
 Publisher publisher = Publisher.newBuilder(topicName).setRetrySettings(retrySettings).build();
 // [END pubsub_publisher_retry_settings]
 return publisher;
}
origin: googleapis/google-cloud-java

/**
 * Set the maximum period a message ack deadline will be extended. Defaults to one hour.
 *
 * <p>It is recommended to set this value to a reasonable upper bound of the subscriber time to
 * process any message. This maximum period avoids messages to be <i>locked</i> by a subscriber
 * in cases when the ack reply is lost.
 *
 * <p>A zero duration effectively disables auto deadline extensions.
 */
public Builder setMaxAckExtensionPeriod(Duration maxAckExtensionPeriod) {
 Preconditions.checkArgument(maxAckExtensionPeriod.toMillis() >= 0);
 this.maxAckExtensionPeriod = maxAckExtensionPeriod;
 return this;
}
origin: googleapis/google-cloud-java

private DurationRule(Duration duration) {
 this.builder =
   com.google.protobuf.Duration.newBuilder()
     .setSeconds(duration.getSeconds())
     .setNanos(duration.getNano());
}
origin: googleapis/google-cloud-java

private void verifyOk(ApiFuture<?> result) {
 Throwable error = null;
 try {
  result.get(FLUSH_PERIOD.plus(DELAY_BUFFER).toMillis(), TimeUnit.MILLISECONDS);
 } catch (ExecutionException e) {
  error = e.getCause();
 } catch (Throwable t) {
  error = t;
 }
 assertThat(error).isNull();
}
origin: googleapis/google-cloud-java

@Test
public void testCreateFromStream() {
 RemoteComputeHelper helper = RemoteComputeHelper.create(PROJECT_ID, JSON_KEY_STREAM);
 ComputeOptions options = helper.getOptions();
 assertEquals(PROJECT_ID, options.getProjectId());
 assertEquals(60000, ((HttpTransportOptions) options.getTransportOptions()).getConnectTimeout());
 assertEquals(60000, ((HttpTransportOptions) options.getTransportOptions()).getReadTimeout());
 assertEquals(10, options.getRetrySettings().getMaxAttempts());
 assertEquals(Duration.ofMillis(30000), options.getRetrySettings().getMaxRetryDelay());
 assertEquals(Duration.ofMillis(120000), options.getRetrySettings().getTotalTimeout());
 assertEquals(Duration.ofMillis(250), options.getRetrySettings().getInitialRetryDelay());
}
origin: googleapis/google-cloud-java

@Test
public void testReadRowsSettings() {
 ServerStreamingCallSettings.Builder<ReadRowsRequest, ReadRowsResponse> builder =
   EnhancedBigQueryStorageStubSettings.newBuilder().readRowsSettings();
 assertThat(builder.getRetryableCodes()).containsAllOf(Code.DEADLINE_EXCEEDED, Code.UNAVAILABLE);
 RetrySettings retrySettings = builder.getRetrySettings();
 assertThat(retrySettings.getInitialRetryDelay()).isEqualTo(Duration.ofMillis(100L));
 assertThat(retrySettings.getRetryDelayMultiplier()).isWithin(1e-6).of(1.3);
 assertThat(retrySettings.getMaxRetryDelay()).isEqualTo(Duration.ofMinutes(1L));
 assertThat(retrySettings.getInitialRpcTimeout()).isEqualTo(Duration.ofDays(1L));
 assertThat(retrySettings.getRpcTimeoutMultiplier()).isWithin(1e-6).of(1.0);
 assertThat(retrySettings.getMaxRpcTimeout()).isEqualTo(Duration.ofDays(1L));
 assertThat(retrySettings.getTotalTimeout()).isEqualTo(Duration.ofDays(1L));
 assertThat(builder.getIdleTimeout()).isEqualTo(Duration.ZERO);
}
origin: googleapis/google-cloud-java

/** Example of partitioning data to a list of Google Cloud Storage files. */
// [TARGET extract(String, List, JobOption...)]
// [VARIABLE "CSV"]
// [VARIABLE "gs://my_bucket/PartitionA_*.csv"]
// [VARIABLE "gs://my_bucket/PartitionB_*.csv"]
public Job extractList(String format, String gcsUrl1, String gcsUrl2) {
 // [START ]
 List<String> destinationUris = new ArrayList<>();
 destinationUris.add(gcsUrl1);
 destinationUris.add(gcsUrl2);
 Job job = table.extract(format, destinationUris);
 // Wait for the job to complete
 try {
  Job completedJob =
    job.waitFor(
      RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
      RetryOption.totalTimeout(Duration.ofMinutes(3)));
  if (completedJob != null && completedJob.getStatus().getError() == null) {
   // Job completed successfully
  } else {
   // Handle error case
  }
 } catch (InterruptedException e) {
  // Handle interrupted wait
 }
 // [END ]
 return job;
}
origin: googleapis/google-cloud-java

@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
 return schedulePendingCallable(
   new PendingCallable<>(
     Duration.ofMillis(unit.toMillis(delay)), command, PendingCallableType.NORMAL));
}
origin: googleapis/google-cloud-java

private AwaitReplicationCallable createAwaitReplicationCallable() {
 // TODO(igorbernstein2): expose polling settings
 RetrySettings pollingSettings =
   RetrySettings.newBuilder()
     // use overall timeout from checkConsistencyCallable
     // NOTE: The overall timeout might exceed this value due to underlying retries
     .setTotalTimeout(
       settings.checkConsistencySettings().getRetrySettings().getTotalTimeout())
     // Use constant polling with jitter
     .setInitialRetryDelay(Duration.ofSeconds(10))
     .setRetryDelayMultiplier(1.0)
     .setMaxRetryDelay(Duration.ofSeconds(10))
     .setJittered(true)
     // These rpc timeouts are ignored, instead the rpc timeouts defined for
     // generateConsistencyToken and checkConsistency callables will be used.
     .setInitialRpcTimeout(Duration.ZERO)
     .setMaxRpcTimeout(Duration.ZERO)
     .setRpcTimeoutMultiplier(1.0)
     .build();
 return AwaitReplicationCallable.create(
   generateConsistencyTokenCallable(),
   checkConsistencyCallable(),
   clientContext,
   pollingSettings);
}
origin: googleapis/google-cloud-java

  RetrySettings.newBuilder()
    .setMaxAttempts(10)
    .setTotalTimeout(Duration.ofHours(1))
    .setInitialRpcTimeout(Duration.ofSeconds(10))
    .setRpcTimeoutMultiplier(1)
    .setMaxRpcTimeout(Duration.ofSeconds(10))
    .setJittered(true)
    .build();
  .setIdleTimeout(Duration.ofMinutes(5))
  .setRetryableCodes(Code.ABORTED, Code.DEADLINE_EXCEEDED)
  .setRetrySettings(retrySettings)
assertThat(builder.readRowsSettings().getIdleTimeout()).isEqualTo(Duration.ofMinutes(5));
assertThat(builder.readRowsSettings().getRetryableCodes())
  .containsAllOf(Code.ABORTED, Code.DEADLINE_EXCEEDED);
  .isEqualTo(Duration.ofMinutes(5));
assertThat(builder.build().readRowsSettings().getRetryableCodes())
  .containsAllOf(Code.ABORTED, Code.DEADLINE_EXCEEDED);
  .isEqualTo(Duration.ofMinutes(5));
assertThat(builder.build().toBuilder().readRowsSettings().getRetryableCodes())
  .containsAllOf(Code.ABORTED, Code.DEADLINE_EXCEEDED);
origin: googleapis/google-cloud-java

 private static Duration systemProperty(String name, int defaultValue) {
  String stringValue = System.getProperty(name, "");
  return Duration.ofSeconds(stringValue.isEmpty() ? defaultValue : Integer.parseInt(stringValue));
 }
}
origin: googleapis/google-cloud-java

@Test(expected = ExecutionException.class)
public void testPublishFailureRetries_retriesDisabled() throws Exception {
 Publisher publisher =
   getTestPublisherBuilder()
     .setExecutorProvider(SINGLE_THREAD_EXECUTOR)
     .setRetrySettings(
       Publisher.Builder.DEFAULT_RETRY_SETTINGS
         .toBuilder()
         .setTotalTimeout(Duration.ofSeconds(10))
         .setMaxAttempts(1)
         .build())
     .build();
 testPublisherServiceImpl.addPublishError(new Throwable("Transiently failing"));
 ApiFuture<String> publishFuture1 = sendTestMessage(publisher, "A");
 try {
  publishFuture1.get();
 } finally {
  assertSame(testPublisherServiceImpl.getCapturedRequests().size(), 1);
  publisher.shutdown();
  publisher.awaitTermination(1, TimeUnit.MINUTES);
 }
}
origin: googleapis/google-cloud-java

MockRetryingFuture(Duration totalTimeout) {
 this.timedAttemptSettings =
   TimedAttemptSettings.newBuilder()
     .setRpcTimeout(Duration.ofSeconds(1))
     .setRetryDelay(Duration.ZERO)
     .setRandomizedRetryDelay(Duration.ZERO)
     .setAttemptCount(0)
     .setFirstAttemptStartTimeNanos(0)
     .setGlobalSettings(RetrySettings.newBuilder().setTotalTimeout(totalTimeout).build())
     .build();
}
origin: com.google.api/gax-httpjson

@Override
public HttpJsonCallContext withTimeout(Duration timeout) {
 // Default RetrySettings use 0 for RPC timeout. Treat that as disabled timeouts.
 if (timeout != null && (timeout.isZero() || timeout.isNegative())) {
  timeout = null;
 }
 // Prevent expanding deadlines
 if (timeout != null && this.timeout != null && this.timeout.compareTo(timeout) <= 0) {
  return this;
 }
 return new HttpJsonCallContext(
   this.channel, timeout, this.deadline, this.credentials, this.extraHeaders, this.tracer);
}
origin: googleapis/gax-java

@Test
public void testTimeoutToDeadlineConversion() {
 MethodDescriptor<Color, Money> descriptor = FakeServiceGrpc.METHOD_RECOGNIZE;
 @SuppressWarnings("unchecked")
 ClientCall<Color, Money> mockClientCall = Mockito.mock(ClientCall.class);
 @SuppressWarnings("unchecked")
 ClientCall.Listener<Money> mockListener = Mockito.mock(ClientCall.Listener.class);
 @SuppressWarnings("unchecked")
 Channel mockChannel = Mockito.mock(ManagedChannel.class);
 ArgumentCaptor<CallOptions> capturedCallOptions = ArgumentCaptor.forClass(CallOptions.class);
 Mockito.when(mockChannel.newCall(Mockito.eq(descriptor), capturedCallOptions.capture()))
   .thenReturn(mockClientCall);
 Duration timeout = Duration.ofSeconds(10);
 Deadline minExpectedDeadline = Deadline.after(timeout.getSeconds(), TimeUnit.SECONDS);
 GrpcCallContext context =
   GrpcCallContext.createDefault().withChannel(mockChannel).withTimeout(timeout);
 GrpcClientCalls.newCall(descriptor, context).start(mockListener, new Metadata());
 Deadline maxExpectedDeadline = Deadline.after(timeout.getSeconds(), TimeUnit.SECONDS);
 Truth.assertThat(capturedCallOptions.getValue().getDeadline()).isAtLeast(minExpectedDeadline);
 Truth.assertThat(capturedCallOptions.getValue().getDeadline()).isAtMost(maxExpectedDeadline);
}
origin: com.google.api/gax

 /**
  * This method simply calls {@link Thread#sleep(long)}.
  *
  * @param delay time to sleep
  * @throws InterruptedException if any thread has interrupted the current thread
  */
 protected void sleep(Duration delay) throws InterruptedException {
  if (Duration.ZERO.compareTo(delay) < 0) {
   Thread.sleep(delay.toMillis());
  }
 }
}
origin: com.google.api/gax

 @SuppressWarnings("ConstantConditions")
 @Nullable
 @Override
 public Watchdog getWatchdog() {
  Preconditions.checkState(!needsClock(), "A clock is needed");
  Preconditions.checkState(!needsCheckInterval(), "A check interval is needed");
  Preconditions.checkState(!needsExecutor(), "An executor is needed");

  // Watchdog is disabled
  if (checkInterval.isZero()) {
   return null;
  }

  Watchdog watchdog = new Watchdog(clock);
  executor.scheduleAtFixedRate(
    watchdog, checkInterval.toMillis(), checkInterval.toMillis(), TimeUnit.MILLISECONDS);

  return watchdog;
 }
}
origin: googleapis/google-cloud-java

  .addFamily("mf2", GCRULES.maxAge(Duration.ofSeconds(1000, 20000)))
  .updateFamily(
    "mf1",
    GCRULES
      .union()
      .rule(GCRULES.maxAge(Duration.ofSeconds(100)))
      .rule(GCRULES.maxVersions(1)))
  .addFamily(
    GCRULES
      .intersection()
      .rule(GCRULES.maxAge(Duration.ofSeconds(2000)))
      .rule(GCRULES.maxVersions(10)))
  .addFamily("mf4", GCRULES.intersection().rule(GCRULES.maxAge(Duration.ofSeconds(360))))
  .addFamily("mf5")
  .addFamily("mf6")
 assertEquals(2, ((UnionRule) columnFamilyById.get("mf1").getGCRule()).getRulesList().size());
 assertEquals(
   1000, ((DurationRule) columnFamilyById.get("mf2").getGCRule()).getMaxAge().getSeconds());
 assertEquals(
   20000, ((DurationRule) columnFamilyById.get("mf2").getGCRule()).getMaxAge().getNano());
 assertEquals(
   2, ((IntersectionRule) columnFamilyById.get("mf3").getGCRule()).getRulesList().size());
 assertEquals(
   360, ((DurationRule) columnFamilyById.get("mf4").getGCRule()).getMaxAge().getSeconds());
 assertNotNull(columnFamilyById.get("mf7"));
} finally {
origin: googleapis/google-cloud-java

/** Configures the Publisher's retry parameters. */
public Builder setRetrySettings(RetrySettings retrySettings) {
 Preconditions.checkArgument(
   retrySettings.getTotalTimeout().compareTo(MIN_TOTAL_TIMEOUT) >= 0);
 Preconditions.checkArgument(
   retrySettings.getInitialRpcTimeout().compareTo(MIN_RPC_TIMEOUT) >= 0);
 this.retrySettings = retrySettings;
 return this;
}
org.threeten.bpDuration

Javadoc

A time-based amount of time, such as '34.5 seconds'.

This class models a quantity or amount of time in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours. In addition, the ChronoUnit#DAYS unit can be used and is treated as exactly equal to 24 hours, thus ignoring daylight savings effects. See Period for the date-based equivalent to this class.

A physical duration could be of infinite length. For practicality, the duration is stored with constraints similar to Instant. The duration uses nanosecond resolution with a maximum value of the seconds that can be held in a long. This is greater than the current estimated age of the universe.

The range of a duration requires the storage of a number larger than a long. To achieve this, the class stores a long representing seconds and an intrepresenting nanosecond-of-second, which will always be between 0 and 999,999,999.

The duration is measured in "seconds", but these are not necessarily identical to the scientific "SI second" definition based on atomic clocks. This difference only impacts durations measured near a leap-second and should not affect most applications. See Instant for a discussion as to the meaning of the second and time-scales.

Specification for implementors

This class is immutable and thread-safe.

Most used methods

  • ofMillis
    Obtains an instance of Duration from a number of milliseconds. The seconds and nanoseconds are extra
  • ofSeconds
    Obtains an instance of Duration from a number of seconds and an adjustment in nanoseconds. This meth
  • toMillis
    Converts this duration to the total length in milliseconds. If this duration is too large to fit in
  • ofMinutes
    Obtains an instance of Duration from a number of standard length minutes. The seconds are calculated
  • compareTo
    Compares this duration to the specified Duration. The comparison is based on the total length of the
  • getSeconds
    Gets the number of seconds in this duration. The length of the duration is stored using two fields -
  • isZero
    Checks if this duration is zero length. A Duration represents a directed distance between two points
  • between
    Obtains an instance of Duration representing the duration between two instants. Obtains a Duration
  • getNano
    Gets the number of nanoseconds within the second in this duration. The length of the duration is sto
  • isNegative
    Checks if this duration is negative, excluding zero. A Duration represents a directed distance betwe
  • toNanos
    Converts this duration to the total length in nanoseconds expressed as a long. If this duration is
  • ofHours
    Obtains an instance of Duration from a number of standard length hours. The seconds are calculated b
  • toNanos,
  • ofHours,
  • ofNanos,
  • equals,
  • of,
  • ofDays,
  • plus,
  • toMinutes,
  • <init>,
  • create

Popular in Java

  • Making http requests using okhttp
  • compareTo (BigDecimal)
  • onRequestPermissionsResult (Fragment)
  • getSystemService (Context)
  • HttpServer (com.sun.net.httpserver)
    This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number a
  • Collections (java.util)
    This class consists exclusively of static methods that operate on or return collections. It contains
  • HashMap (java.util)
    HashMap is an implementation of Map. All optional operations are supported.All elements are permitte
  • Timer (java.util)
    Timers schedule one-shot or recurring TimerTask for execution. Prefer java.util.concurrent.Scheduled
  • IOUtils (org.apache.commons.io)
    General IO stream manipulation utilities. This class provides static utility methods for input/outpu
  • Logger (org.slf4j)
    The org.slf4j.Logger interface is the main user entry point of SLF4J API. It is expected that loggin
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now