当前位置: 首页>>代码示例>>Java>>正文


Java Period类代码示例

本文整理汇总了Java中org.joda.time.Period的典型用法代码示例。如果您正苦于以下问题:Java Period类的具体用法?Java Period怎么用?Java Period使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Period类属于org.joda.time包,在下文中一共展示了Period类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: formatDuration

import org.joda.time.Period; //导入依赖的package包/类
public static String formatDuration(long duration)
{
	// Using Joda Time
	DateTime now = new DateTime(); // Now
	DateTime plus = now.plus(new Duration(duration * 1000));

	// Define and calculate the interval of time
	Interval interval = new Interval(now.getMillis(), plus.getMillis());
	Period period = interval.toPeriod(PeriodType.time());

	// Define the period formatter for pretty printing
	String ampersand = " & ";
	PeriodFormatter pf = new PeriodFormatterBuilder().appendHours().appendSuffix(ds("hour"), ds("hours"))
		.appendSeparator(" ", ampersand).appendMinutes().appendSuffix(ds("minute"), ds("minutes"))
		.appendSeparator(ampersand).appendSeconds().appendSuffix(ds("second"), ds("seconds")).toFormatter();

	return pf.print(period).trim();
}
 
开发者ID:equella,项目名称:Equella,代码行数:19,代码来源:EchoUtils.java

示例2: testTimeSpanFromPeriod

import org.joda.time.Period; //导入依赖的package包/类
@Test
public void testTimeSpanFromPeriod() {
    Period period = new Period()
            .withDays(366)
            .withHours(25)
            .withMinutes(10)
            .withSeconds(70)
            .withMillis(1001);
    TimeSpan timeSpan = new TimeSpan()
            .withDays(366)
            .withHours(25)
            .withMinutes(10)
            .withSeconds(70)
            .withMilliseconds(1001);
    Assert.assertEquals(TimeSpan.fromPeriod(period).toString(), timeSpan.toString());

    period = new Period()
            .withWeeks(12)
            .withDays(366)
            .withHours(25)
            .withMinutes(10)
            .withSeconds(70)
            .withMillis(1001);
    // Days -> 12 * 7 + 366 + 1
    Assert.assertEquals("451.01:11:11.0010000", TimeSpan.fromPeriod(period).toString());
}
 
开发者ID:Azure,项目名称:azure-libraries-for-java,代码行数:27,代码来源:TimeSpanTests.java

示例3: unregisteredAfterTimeout

import org.joda.time.Period; //导入依赖的package包/类
private KubernetesAgentInstances unregisteredAfterTimeout(PluginSettings settings, Agents knownAgents) throws Exception {
    Period period = settings.getAutoRegisterPeriod();
    KubernetesAgentInstances unregisteredInstances = new KubernetesAgentInstances();
    KubernetesClient client = factory.kubernetes(settings);

    for (String instanceName : instances.keySet()) {
        if (knownAgents.containsAgentWithId(instanceName)) {
            continue;
        }
        Pod pod = client.pods().inNamespace(Constants.KUBERNETES_NAMESPACE_KEY).withName(instanceName).get();
        Date createdAt = getSimpleDateFormat().parse(pod.getMetadata().getCreationTimestamp());
        DateTime dateTimeCreated = new DateTime(createdAt);

        if (clock.now().isAfter(dateTimeCreated.plus(period))) {
            unregisteredInstances.register(kubernetesInstanceFactory.fromKubernetesPod(pod));
        }
    }
    return unregisteredInstances;
}
 
开发者ID:gocd,项目名称:kubernetes-elastic-agents,代码行数:20,代码来源:KubernetesAgentInstances.java

示例4: testShouldTerminateInstancesThatNeverAutoRegistered

import org.joda.time.Period; //导入依赖的package包/类
@Test
public void testShouldTerminateInstancesThatNeverAutoRegistered() throws Exception {
    KubernetesAgentInstances agentInstances = new KubernetesAgentInstances(factory);
    HashMap<String, String> properties = new HashMap<>();
    properties.put("Image", "foo");
    KubernetesInstance container = agentInstances.create(new CreateAgentRequest(null, properties, null, new JobIdentifier(1L)), createSettings(), null);

    agentInstances.clock = new Clock.TestClock().forward(Period.minutes(11));
    PluginRequest pluginRequest = mock(PluginRequest.class);

    objectMetadata.setName(container.name());
    HashMap<String, String> labels = new HashMap<>();
    labels.put(Constants.JOB_ID_LABEL_KEY, "1");
    objectMetadata.setLabels(labels);
    when(pluginRequest.getPluginSettings()).thenReturn(createSettings());
    when(pluginRequest.listAgents()).thenReturn(new Agents());
    verifyNoMoreInteractions(pluginRequest);

    new ServerPingRequestExecutor(agentInstances, pluginRequest).execute();
    assertFalse(agentInstances.instanceExists(container));
}
 
开发者ID:gocd,项目名称:kubernetes-elastic-agents,代码行数:22,代码来源:ServerPingRequestExecutorTest.java

示例5: testParquetReaderHelper

import org.joda.time.Period; //导入依赖的package包/类
private void testParquetReaderHelper(String tableName, Period row1Col1, Period row1Col2,
                                     Period row2Col1, Period row2Col2) throws Exception {

  final String switchReader = "alter session set `store.parquet.use_new_reader` = %s; ";
  final String enableVectorizedReader = String.format(switchReader, true);
  final String disableVectorizedReader = String.format(switchReader, false);
  String query = String.format("select * from %s", tableName);

  testBuilder()
      .sqlQuery(query)
      .unOrdered()
      .optionSettingQueriesForTestQuery(enableVectorizedReader)
      .baselineColumns("col1", "col2")
      .baselineValues(row1Col1, row1Col2)
      .baselineValues(row2Col1, row2Col2)
      .go();

  testBuilder()
      .sqlQuery(query)
      .unOrdered()
      .optionSettingQueriesForTestQuery(disableVectorizedReader)
      .baselineColumns("col1", "col2")
      .baselineValues(row1Col1, row1Col2)
      .baselineValues(row2Col1, row2Col2)
      .go();
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:27,代码来源:TestParquetWriter.java

示例6: putDurationValidWithServiceResponseAsync

import org.joda.time.Period; //导入依赖的package包/类
/**
 * Set dictionary value  {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}.
 *
 * @param arrayBody the Map&lt;String, Period&gt; value
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<ServiceResponse<Void>> putDurationValidWithServiceResponseAsync(Map<String, Period> arrayBody) {
    if (arrayBody == null) {
        throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null.");
    }
    Validator.validate(arrayBody);
    return service.putDurationValid(arrayBody)
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
            @Override
            public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Void> clientResponse = putDurationValidDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
 
开发者ID:Azure,项目名称:autorest.java,代码行数:26,代码来源:DictionarysImpl.java

示例7: unregisteredAfterTimeout

import org.joda.time.Period; //导入依赖的package包/类
private MarathonAgentInstances unregisteredAfterTimeout(PluginSettings settings, Agents knownAgents) throws Exception {
    MarathonAgentInstances unregisteredContainers = new MarathonAgentInstances();
    if (settings == null) {
        return unregisteredContainers;
    }
    Period period = settings.getAutoRegisterPeriod();

    for (MarathonInstance instance: instances.values()) {
        if (knownAgents.containsAgentWithId(instance.name())) {
            continue;
        }

        DateTime dateTimeCreated = new DateTime(instance.createdAt());

        if (clock.now().isAfter(dateTimeCreated.plus(period))) {
            unregisteredContainers.register(instance);
        }
    }
    return unregisteredContainers;
}
 
开发者ID:pikselpalette,项目名称:gocd-elastic-agent-marathon,代码行数:21,代码来源:MarathonAgentInstances.java

示例8: formatIntervalDay

import org.joda.time.Period; //导入依赖的package包/类
/**
 * Formats a period similar to Oracle INTERVAL DAY TO SECOND data type.<br>
 * For example, the string "-001 18:25:16.766" defines an interval of - 1 day 18 hours 25 minutes 16 seconds and 766 milliseconds
 */
public static String formatIntervalDay(final Period p) {
  long millis = p.getDays() * (long) DateUtility.daysToStandardMillis + DateUtility.millisFromPeriod(p);

  boolean neg = false;
  if (millis < 0) {
    millis = -millis;
    neg = true;
  }

  final int days = (int) (millis / DateUtility.daysToStandardMillis);
  millis = millis % DateUtility.daysToStandardMillis;

  final int hours  = (int) (millis / DateUtility.hoursToMillis);
  millis     = millis % DateUtility.hoursToMillis;

  final int minutes = (int) (millis / DateUtility.minutesToMillis);
  millis      = millis % DateUtility.minutesToMillis;

  final int seconds = (int) (millis / DateUtility.secondsToMillis);
  millis      = millis % DateUtility.secondsToMillis;

  return String.format("%c%03d %02d:%02d:%02d.%03d", neg ? '-':'+', days, hours, minutes, seconds, millis);
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:28,代码来源:DremioStringUtils.java

示例9: putDurationValidWithServiceResponseAsync

import org.joda.time.Period; //导入依赖的package包/类
/**
 * Set array value  ['P123DT22H14M12.011S', 'P5DT1H0M0S'].
 *
 * @param arrayBody the List&lt;Period&gt; value
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<ServiceResponse<Void>> putDurationValidWithServiceResponseAsync(List<Period> arrayBody) {
    if (arrayBody == null) {
        throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null.");
    }
    Validator.validate(arrayBody);
    return service.putDurationValid(arrayBody)
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
            @Override
            public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Void> clientResponse = putDurationValidDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
 
开发者ID:Azure,项目名称:autorest.java,代码行数:26,代码来源:ArraysImpl.java

示例10: refreshAll

import org.joda.time.Period; //导入依赖的package包/类
@Override
public void refreshAll(PluginRequest pluginRequest) throws Exception {
    if (refreshed) {
        if (refreshedTime == null) {
            setRefreshed(false);
        } else {
            if (refreshedTime.isBefore(new DateTime().minus(new Period("PT10M")))) {
                setRefreshed(false);
            }
        }
    }
    if (!refreshed) {
        PluginSettings settings = pluginRequest.getPluginSettings();
        List<MarathonInstance> marathonInstanceList = marathon(settings).getGoAgents(settings);
        for (MarathonInstance instance: marathonInstanceList) {
             register(instance);
        }
        LOG.debug("Instances found: " + marathonInstanceList.toString());
        setRefreshedTime(new DateTime());
        setRefreshed(true);
    }
}
 
开发者ID:pikselpalette,项目名称:gocd-elastic-agent-marathon,代码行数:23,代码来源:MarathonAgentInstances.java

示例11: getDelay

import org.joda.time.Period; //导入依赖的package包/类
/**
 * Decide when the job should start run in first time
 * @return Seconds for the Job to start
 */
public int getDelay() {
  try {
    JobRunInfo lastRun = jobInfoStore.getLatestRun(this.identifier);

    if (lastRun != null && lastRun.isSucceed()) {
      Period
          period =
          new Period(new DateTime(lastRun.getStartTime()), DateTime.now(DateTimeZone.UTC));
      if (period.toStandardSeconds().getSeconds() < this.interval) {
        return (int) (this.interval - period.toStandardSeconds().getSeconds());
      }
    }
  } catch (Exception ex) {
    logger.error(ExceptionUtils.getRootCauseMessage(ex));
    logger.error(ExceptionUtils.getFullStackTrace(ex));
  }

  return random.nextInt(Configuration.getProperties().getInt("job_random_delay", 60));
}
 
开发者ID:pinterest,项目名称:soundwave,代码行数:24,代码来源:ExclusiveRecurringJobExecutor.java

示例12: getPositiveDurationWithServiceResponseAsync

import org.joda.time.Period; //导入依赖的package包/类
/**
 * Get a positive duration value.
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the observable to the Period object
 */
public Observable<ServiceResponse<Period>> getPositiveDurationWithServiceResponseAsync() {
    return service.getPositiveDuration()
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Period>>>() {
            @Override
            public Observable<ServiceResponse<Period>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Period> clientResponse = getPositiveDurationDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
 
开发者ID:Azure,项目名称:autorest.java,代码行数:21,代码来源:DurationsImpl.java

示例13: defaultMessageTtlDuration

import org.joda.time.Period; //导入依赖的package包/类
@Override
public Period defaultMessageTtlDuration() {
    if (this.inner().defaultMessageTimeToLive() == null) {
        return null;
    }
    TimeSpan timeSpan = TimeSpan.parse(this.inner().defaultMessageTimeToLive());
    return new Period()
            .withDays(timeSpan.days())
            .withHours(timeSpan.hours())
            .withMinutes(timeSpan.minutes())
            .withSeconds(timeSpan.seconds())
            .withMillis(timeSpan.milliseconds());
}
 
开发者ID:Azure,项目名称:azure-libraries-for-java,代码行数:14,代码来源:ServiceBusSubscriptionImpl.java

示例14: shutdownExecution

import org.joda.time.Period; //导入依赖的package包/类
/**
 * Executes the actual shutdown once one of the shutdown handlers has
 * accepted the shutdown request
 * 
 * @param response
 *            Tells the caller some metrics
 */
private void shutdownExecution(final HttpServerResponse response) {
	final JsonObject goodby = new JsonObject();
	goodby.put("Goodby", "It was a pleasure doing business with you");
	goodby.put("StartDate", Utils.getDateString(this.startDate));
	goodby.put("EndDate", Utils.getDateString(new Date()));
	final Duration dur = new Duration(new DateTime(this.startDate), new DateTime());
	goodby.put("Duration", PeriodFormat.getDefault().print(new Period(dur)));
	response.putHeader(Constants.CONTENT_HEADER, Constants.CONTENT_TYPE_JSON).setStatusCode(202)
			.end(goodby.encodePrettily());
	try {
		Future<Void> shutdownFuture = Future.future();
		shutdownFuture.setHandler(fResult -> {
			if (fResult.failed()) {
				this.logger.fatal(fResult.cause());
				System.exit(-1);
			}
			this.logger.info("Good by!");
			this.getVertx().close(handler -> {
				if (handler.failed()) {
					this.logger.fatal(handler.cause());
				}
				System.exit(0);
			});
		});
		this.shutDownVerticles(shutdownFuture);
	} catch (Exception e) {
		this.logger.fatal(e.getMessage(), e);
	}
}
 
开发者ID:Stwissel,项目名称:vertx-sfdc-platformevents,代码行数:37,代码来源:ApplicationStarter.java

示例15: getDurationValidAsync

import org.joda.time.Period; //导入依赖的package包/类
/**
 * Get duration array value ['P123DT22H14M12.011S', 'P5DT1H0M0S'].
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the observable to the List&lt;Period&gt; object
 */
public Observable<List<Period>> getDurationValidAsync() {
    return getDurationValidWithServiceResponseAsync().map(new Func1<ServiceResponse<List<Period>>, List<Period>>() {
        @Override
        public List<Period> call(ServiceResponse<List<Period>> response) {
            return response.body();
        }
    });
}
 
开发者ID:Azure,项目名称:autorest.java,代码行数:15,代码来源:ArraysImpl.java


注:本文中的org.joda.time.Period类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。