java.time.Clock类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(9.0k)|赞(0)|评价(0)|浏览(177)

本文整理了Java中java.time.Clock类的一些代码示例,展示了Clock类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Clock类的具体详情如下:
包路径:java.time.Clock
类名称:Clock

Clock介绍

[英]A clock providing access to the current instant, date and time using a time-zone.

Instances of this class are used to find the current instant, which can be interpreted using the stored time-zone to find the current date and time. As such, a clock can be used instead of System#currentTimeMillis()and TimeZone#getDefault().

Use of a Clock is optional. All key date-time classes also have a now() factory method that uses the system clock in the default time zone. The primary purpose of this abstraction is to allow alternate clocks to be plugged in as and when required. Applications use an object to obtain the current time rather than a static method. This can simplify testing.

Best practice for applications is to pass a Clock into any method that requires the current instant. A dependency injection framework is one way to achieve this:

public class MyBean { 
private Clock clock;  // dependency inject 
... 
public void process(LocalDate eventDate) { 
if (eventDate.isBefore(LocalDate.now(clock)) { 
... 
} 
} 
}

This approach allows an alternate clock, such as #fixed(Instant,ZoneId)or #offset(Clock,Duration) to be used during testing.

The system factory methods provide clocks based on the best available system clock This may use System#currentTimeMillis(), or a higher resolution clock if one is available.

Specification for implementors

This abstract class must be implemented with care to ensure other operate correctly. All implementations that can be instantiated must be final, immutable and thread-safe.

The principal methods are defined to allow the throwing of an exception. In normal use, no exceptions will be thrown, however one possible implementation would be to obtain the time from a central time server across the network. Obviously, in this case the lookup could fail, and so the method is permitted to throw an exception.

The returned instants from Clock work on a time-scale that ignores leap seconds. If the implementation wraps a source that provides leap second information, then a mechanism should be used to "smooth" the leap second, such as UTC-SLS.

Implementations should implement Serializable wherever possible and must document whether or not they do support serialization.
[中]一种时钟,通过时区提供对当前时刻、日期和时间的访问。
此类的实例用于查找当前时刻,可以使用存储的时区来解释当前时刻以查找当前日期和时间。因此,可以使用时钟代替System#currentTimeMillis()和TimeZone#getDefault()。
使用时钟是可选的。所有关键日期时间类都有一个now()工厂方法,该方法使用默认时区中的系统时钟。此抽象的主要目的是允许在需要时插入备用时钟。应用程序使用对象来获取当前时间,而不是静态方法。这可以简化测试。
应用程序的最佳实践是将时钟传递到任何需要当前瞬间的方法中。依赖项注入框架是实现这一点的一种方法:

public class MyBean { 
private Clock clock;  // dependency inject 
... 
public void process(LocalDate eventDate) { 
if (eventDate.isBefore(LocalDate.now(clock)) { 
... 
} 
} 
}

此方法允许在测试期间使用备用时钟,例如#固定(即时、区域ID)或#偏移(时钟、持续时间)。
系统工厂方法提供基于最佳可用系统时钟的时钟,这可能使用system#currentTimeMillis(),或更高分辨率的时钟(如果有)。
####实施者规范
必须小心地实现该抽象类,以确保其他抽象类正确运行。所有可以实例化的实现都必须是最终的、不可变的和线程安全的。
主要方法被定义为允许抛出异常。在正常使用中,不会引发异常,但是一种可能的实现是通过网络从中央时间服务器获取时间。显然,在这种情况下,查找可能会失败,因此允许该方法引发异常。
时钟返回的瞬间在忽略闰秒的时间刻度上工作。如果实现封装了提供闰秒信息的源,则应使用一种机制“平滑”闰秒,如UTC-SLS。
实现应该尽可能实现可序列化,并且必须记录它们是否支持序列化。

代码示例

代码示例来源:origin: line/armeria

private static long currentTimeMicros() {
    if (PlatformDependent.javaVersion() == 8) {
      return TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
    } else {
      // Java 9+ support higher precision wall time.
      final Instant now = Clock.systemUTC().instant();
      return TimeUnit.SECONDS.toMicros(now.getEpochSecond()) + TimeUnit.NANOSECONDS.toMicros(
          now.getNano());
    }
  }
}

代码示例来源:origin: neo4j/neo4j

private SuspendedTransaction( ActiveTransaction activeMarker, TransactionHandle transactionHandle )
{
  this.activeMarker = activeMarker;
  this.transactionHandle = transactionHandle;
  this.lastActiveTimestamp = clock.millis();
}

代码示例来源:origin: yu199195/Raincat

/**
 * 获得当前的时间戳.
 *
 * @return 时间点
 */
public static Instant nowTimestamp() {
  return Instant.now(Clock.systemDefaultZone());
}

代码示例来源:origin: yu199195/Raincat

/**
 * 获得当前的日期毫秒.
 *
 * @return 当前毫秒数
 */
public static long nowTimeMillis() {
  return Clock.systemDefaultZone().millis();
}

代码示例来源:origin: apache/flume

public SyslogUtils(Integer defaultSize, Set<String> keepFields, boolean isUdp) {
 this(defaultSize, keepFields, isUdp, Clock.system(Clock.systemDefaultZone().getZone()));
}

代码示例来源:origin: yu199195/Raincat

/**
 * 获取从1970年到现在的秒数.
 *
 * @return 秒数
 */
public static long nowEpochSecond() {
  return Clock.systemDefaultZone().instant().getEpochSecond();
}

代码示例来源:origin: neo4j/neo4j

@Test
public void dontThrottleMethodsReturningVoid()
{
  when( clock.millis() ).thenReturn( 100L );
  proxy.returnVoid();
  proxy.returnVoid();
  verify( target, times( 2 ) ).returnVoid();
  verifyNoMoreInteractions( target );
}

代码示例来源:origin: sixt/ja-micro

@Before
public void setup() {
  clock = mock(Clock.class);
  when(clock.instant()).thenReturn(Instant.now());
  when(clock.getZone()).thenReturn(ZoneId.systemDefault());
  consumer = mock(KafkaConsumer.class);
  committer = new OffsetCommitter(consumer, clock);
}

代码示例来源:origin: neo4j/neo4j

public static BoltStateMachine newMachineWithTransactionSPI( TransactionStateMachineSPI transactionSPI ) throws
    AuthenticationException, BoltConnectionFatality
{
  BoltStateMachineSPI spi = mock( BoltStateMachineSPI.class, RETURNS_MOCKS );
  when( spi.transactionSpi() ).thenReturn( transactionSPI );
  BoltChannel boltChannel = BoltTestUtil.newTestBoltChannel();
  BoltStateMachine machine = new BoltStateMachineV1( spi, boltChannel, Clock.systemUTC() );
  init( machine );
  return machine;
}

代码示例来源:origin: neo4j/neo4j

@Test
void shouldCacheValues() throws IOException
{
  final Clock clock = mock( Clock.class );
  storeSizeBean = StoreSizeBean.createBean( managementData, false, 100, clock );
  when( clock.millis() ).thenReturn( 100L );
  createFileOfSize( logFiles.getLogFileForVersion( 0 ), 1 );
  createFileOfSize( logFiles.getLogFileForVersion( 1 ), 2 );
  Assert.assertEquals( 3L, storeSizeBean.getTransactionLogsSize() );
  createFileOfSize( logFiles.getLogFileForVersion( 2 ), 3 );
  createFileOfSize( logFiles.getLogFileForVersion( 3 ), 4 );
  Assert.assertEquals( 3L, storeSizeBean.getTransactionLogsSize() );
  when( clock.millis() ).thenReturn( 200L );
  Assert.assertEquals( 10L, storeSizeBean.getTransactionLogsSize() );
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldCloseBoltChannelWhenClosed()
{
  BoltStateMachineV1SPI spi = mock( BoltStateMachineV1SPI.class );
  BoltChannel boltChannel = mock( BoltChannel.class );
  BoltStateMachine machine = new BoltStateMachineV1( spi, boltChannel, Clock.systemUTC() );
  machine.close();
  verify( boltChannel ).close();
}

代码示例来源:origin: confluentinc/ksql

private Supplier<Boolean> getActivenessCheck() {
 when(clock.millis()).thenReturn(NOW);
 ksqlVersionCheckerAgent.start(KsqlModuleType.SERVER, properties);
 verify(versionCheckerFactory).create(any(), any(), anyBoolean(), activenessCaptor.capture());
 return activenessCaptor.getValue();
}

代码示例来源:origin: neo4j/neo4j

private static BoltStateMachineV1Context newContext( BoltStateMachine machine, BoltStateMachineSPI boltSPI )
  {
    BoltChannel boltChannel = new BoltChannel( "bolt-1", "bolt", mock( Channel.class ) );
    return new BoltStateMachineV1Context( machine, boltChannel, boltSPI, new MutableConnectionState(), Clock.systemUTC() );
  }
}

代码示例来源:origin: neo4j/neo4j

@Test
public void givenAccessGuardWith2ConditionsWhenAwaitThenActuallyWaitGivenTimeout()
{
  // Given
  Log log = mock( Log.class );
  DatabaseAvailabilityGuard databaseAvailabilityGuard = getDatabaseAvailabilityGuard( clock, log );
  databaseAvailabilityGuard.require( REQUIREMENT_1 );
  databaseAvailabilityGuard.require( REQUIREMENT_2 );
  // When
  long timeout = 1000;
  long start = clock.millis();
  boolean result = databaseAvailabilityGuard.isAvailable( timeout );
  long end = clock.millis();
  // Then
  long waitTime = end - start;
  assertThat( result, equalTo( false ) );
  assertThat( waitTime, greaterThanOrEqualTo( timeout ) );
}

代码示例来源:origin: confluentinc/ksql

private void givenLastRequest(final long at) {
 when(clock.millis()).thenReturn(at);
 ksqlVersionCheckerAgent.updateLastRequestTime();
 when(clock.millis()).thenReturn(NOW);
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void set_created_after_from_created_since() {
 Date now = DateUtils.parseDateTime("2013-07-25T07:35:00+0100");
 when(clock.instant()).thenReturn(now.toInstant());
 when(clock.getZone()).thenReturn(ZoneOffset.UTC);
 SearchRequest request = new SearchRequest()
  .setCreatedInLast("1y2m3w4d");
 assertThat(underTest.create(request).createdAfter().date()).isEqualTo(DateUtils.parseDateTime("2012-04-30T07:35:00+0100"));
 assertThat(underTest.create(request).createdAfter().inclusive()).isTrue();
}

代码示例来源:origin: neo4j/neo4j

@BeforeEach
void setUp()
{
  state.setStreamingState( streamingState );
  state.setInterruptedState( interruptedState );
  state.setFailedState( failedState );
  when( context.connectionState() ).thenReturn( connectionState );
  when( context.clock() ).thenReturn( Clock.systemUTC() );
  connectionState.setStatementProcessor( statementProcessor );
}

代码示例来源:origin: apache/flink

@Test
public void testElapsedTime() {
  final long elapsedTime = new TransactionHolder<>(new Object(), 0)
    .elapsedTime(Clock.fixed(Instant.ofEpochMilli(1000), ZoneOffset.UTC));
  assertThat(elapsedTime, equalTo(1000L));
}

代码示例来源:origin: org.vesalainen.nmea/parser

/**
 * Creates a GPSClock in live or fixed mode depending on argument.
 * @param live 
 */
public GPSClock(boolean live)
{
  this(live ? Clock.systemUTC() : Clock.fixed(Instant.now(), ZoneOffset.UTC));
}

代码示例来源:origin: org.mutabilitydetector/MutabilityDetector

public TimingUtil() {
  long jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
  jvmStartTimeClock = Clock.fixed(Instant.ofEpochMilli(jvmStartTime), ZoneId.systemDefault());
  currentTimeClock = Clock.systemDefaultZone();
}

相关文章