Example usage for org.joda.time Period minutes

List of usage examples for org.joda.time Period minutes

Introduction

In this page you can find the example usage for org.joda.time Period minutes.

Prototype

public static Period minutes(int minutes) 

Source Link

Document

Create a period with a specified number of minutes.

Usage

From source file:com.google.code.tickconverter.convert.ConvertAdapter.java

License:Open Source License

/**
 * This method is the main method of the convert process. While the {@link BlockingQueue} of {@link IDukascopyRO}
 * have for 10 seconds no objects in the {@link BlockingQueue} add this method this object into the
 * {@link MetatraderConverter}. If an {@link InvalidTimeException} will threw the converter put a new
 * {@link MetatraderBean} into the {@link BlockingQueue} of {@link IMetatraderRO} and get the information of the
 * values from the {@link MetatraderConverter} object.
 * // www . j  a va 2  s. co  m
 * @throws InterruptedException will threw if {@link Thread#interrupt()} is called in the poll phase
 * @throws InvalidTimeException will threw if {@link MetatraderConverter#incrementInterval()} have a low range for
 *             the new object after the creation of a new {@link MetatraderBean}
 */
public void convertProcess() throws InterruptedException {
    while (true) {
        IDukascopyRO object = dukaQueue.poll(2, TimeUnit.SECONDS);
        LoggerUtils.createDebugLog("poll object: " + object);
        if (null == object) {
            if (null != converter && converter.hasElements()) {
                putMetatraderObject();
            }

            break;
        }

        if (null == converter) {
            DateTime timestamp = object.getTimeStamp();
            DateTime start = new DateTime(timestamp.get(DateTimeFieldType.year()),
                    timestamp.get(DateTimeFieldType.monthOfYear()),
                    timestamp.get(DateTimeFieldType.dayOfMonth()), timestamp.get(DateTimeFieldType.hourOfDay()),
                    timestamp.get(DateTimeFieldType.minuteOfHour()));
            converter = new MetatraderConverter(start, Period.minutes(1));
        }
        try {
            converter.addDukascopy(object);
        } catch (InvalidTimeException e) {
            putMetatraderObject();
            incrementWhileAdd(object);
        }
    }
}

From source file:com.microsoft.azurebatch.jenkins.azurebatch.AzureBatchHelper.java

License:Open Source License

/**
 * Create an pool via creating a Batch job with auto pool. We set an initial timeout for the pool life, and will extend it to add 
 * extra timeout from the task job. We use auto pool to help manage the life cycle of pool, so even when Jenkins server has some
 * issue, the life cycle of pool will be limited, and customers won't be charged for that. Creating pool and VMs could be time consuming,
 * we use a separate pool job to create pool at earliest possible, and in future, we plan to allow customers to create pool in earlier
 * step in Jenkins project, say, during building step, which will help improve the start up experience.
 * @param poolSpecOsFamily Os Family//from   w w  w .j  a  v a2s.c  o  m
 * @param poolSpecTargetOSVersion Target OS version, see more <a href="https://azure.microsoft.com/documentation/articles/batch-api-basics/">here</a>
 * @param poolSpecTargetDedicated Target dedicated, see more <a href="https://azure.microsoft.com/documentation/articles/batch-api-basics/">here</a>
 * @param poolSpecVmSize VM size, see more <a href="https://azure.microsoft.com/documentation/articles/batch-api-basics/">here</a>
 * @param poolSpecAutoPoolKeepAlive Keep auto pool alive, see more <a href="https://azure.microsoft.com/documentation/articles/batch-api-basics/">here</a>
 * @param poolSpecMaxTasksPerNode Max tasks per VM, see more <a href="https://azure.microsoft.com/documentation/articles/batch-api-basics/">here</a>
 * @param poolTimeoutInMin Timeout in minutes of the pool, see more <a href="https://azure.microsoft.com/documentation/articles/batch-api-basics/">here</a>
 * @throws BatchErrorException
 * @throws IOException
 * @throws InterruptedException
 * @throws TimeoutException 
 */
private void createJobWithAutoPool(String poolSpecOsFamily, String poolSpecTargetOSVersion,
        int poolSpecTargetDedicated, String poolSpecVmSize, boolean poolSpecAutoPoolKeepAlive,
        int poolSpecMaxTasksPerNode, int poolTimeoutInMin)
        throws BatchErrorException, IOException, InterruptedException, TimeoutException {
    Logger.log(listener, "Creating auto pool for poolJob %s", poolJobId);

    Logger.log(listener, "Set CloudServiceConfiguration: OsFamily %s, TargetOSVersion %s", poolSpecOsFamily,
            poolSpecTargetOSVersion);
    CloudServiceConfiguration cloudServiceConfiguration = new CloudServiceConfiguration();
    cloudServiceConfiguration.withOsFamily(poolSpecOsFamily).withTargetOSVersion(poolSpecTargetOSVersion);

    Logger.log(listener, "Set PoolSpecification: TargetDedicated %d, VmSize %s", poolSpecTargetDedicated,
            poolSpecVmSize);
    PoolSpecification poolSpecification = new PoolSpecification();
    poolSpecification.withTargetDedicated(poolSpecTargetDedicated).withVmSize(poolSpecVmSize)
            .withMaxTasksPerNode(poolSpecMaxTasksPerNode)
            .withCloudServiceConfiguration(cloudServiceConfiguration);

    Logger.log(listener, "Set AutoPoolSpecification: AutoPoolIdPrefix %s, KeepAlive %b", getAutoPoolIdPrefix(),
            poolSpecAutoPoolKeepAlive);
    AutoPoolSpecification autoPoolSpecification = new AutoPoolSpecification();
    autoPoolSpecification.withAutoPoolIdPrefix(getAutoPoolIdPrefix()).withKeepAlive(poolSpecAutoPoolKeepAlive)
            .withPoolLifetimeOption(PoolLifetimeOption.JOB).withPool(poolSpecification);

    PoolInformation poolInformation = new PoolInformation();
    poolInformation.withAutoPoolSpecification(autoPoolSpecification);

    // Set timeout for the job so it won't run forever even when there's issue with the tests
    JobConstraints jobConstraints = new JobConstraints();
    jobConstraints.withMaxWallClockTime(Period.minutes(poolTimeoutInMin));
    Logger.log(listener, "Set poolJob %s constraints with timeout %d minutes.", poolJobId, poolTimeoutInMin);

    JobAddParameter param = new JobAddParameter();
    param.withId(poolJobId).withPoolInfo(poolInformation).withConstraints(jobConstraints);

    client.jobOperations().createJob(param);
    Logger.log(listener, "PoolJob %s is created.", poolJobId);
}

From source file:com.microsoft.azurebatch.jenkins.azurebatch.AzureBatchHelper.java

License:Open Source License

/**
 * Extend pool job's timeout/*from  w  w w . j a v a  2 s . c  om*/
 * @param extraTimeoutInMin Extra timeout in minutes
 * @throws BatchErrorException
 * @throws IOException 
 */
private void extendPoolJobTimeout(int extraTimeoutInMin) throws BatchErrorException, IOException {
    CloudJob job = client.jobOperations().getJob(poolJobId);

    DateTime jobCreatedTime = job.creationTime();
    DateTime now = new DateTime(DateTimeZone.UTC);

    // Add some safe buffer timeout to the new job timeout
    final int safeMoreTimeoutInMin = 15;
    int newJobTimeoutInMin = (int) ((now.getMillis() - jobCreatedTime.getMillis()) / 1000 / 60)
            + extraTimeoutInMin + safeMoreTimeoutInMin;

    JobConstraints jobConstraints = new JobConstraints();
    jobConstraints.withMaxWallClockTime(Period.minutes(newJobTimeoutInMin));

    JobPatchParameter jpp = new JobPatchParameter();
    jpp.withConstraints(jobConstraints);

    client.jobOperations().patchJob(poolJobId, jpp);
    Logger.log(listener, "Set poolJob %s new timeout to %d minutes.", poolJobId, newJobTimeoutInMin);
}

From source file:com.microsoft.azurebatch.jenkins.azurebatch.AzureBatchHelper.java

License:Open Source License

private void tryToShrinkPool(String poolId, int waitTimeoutInMin, List<CloudTask> taskCollection)
        throws BatchErrorException, IOException {
    // Try to down scale pool size if we don't have active tasks but have idle VMs.
    boolean toResize = true;
    for (CloudTask task : taskCollection) {
        if (task.state() == TaskState.ACTIVE) {
            // If there's still some task in active, we don't need to resize.
            toResize = false;/*  ww w.  j  ava  2 s.  c  o  m*/
            break;
        }
    }

    if (toResize) {
        CloudPool pool = client.poolOperations().getPool(poolId);

        if (pool.allocationState() == AllocationState.STEADY) {
            Logger.log(listener, "Shrinking pool since we dont't have active tasks but have idle VMs...");

            client.poolOperations().resizePool(poolId, 0, Period.minutes(waitTimeoutInMin),
                    ComputeNodeDeallocationOption.TASKCOMPLETION);
        }
    }
}

From source file:com.microsoft.azurebatch.jenkins.azurebatch.JobGenerator.java

License:Open Source License

private void createJobWithTasks(int jobCompletedTimeoutInMin, JobPreparationTask jobPreparationTask,
        List<TaskAddParameter> taskList)
        throws BatchErrorException, IOException, InterruptedException, TimeoutException {
    Logger.log(listener, "Create job %s with pool: %s", jobId, poolId);

    PoolInformation poolInformation = new PoolInformation();
    poolInformation.withPoolId(poolId);//from  w  w w .j a  va  2 s.c om

    JobConstraints jobConstraints = new JobConstraints();
    jobConstraints.withMaxWallClockTime(Period.minutes(jobCompletedTimeoutInMin));
    Logger.log(listener, "Set job %s constraints with timeout %d minutes.", jobId, jobCompletedTimeoutInMin);

    JobAddParameter param = new JobAddParameter();
    param.withId(jobId).withJobPreparationTask(jobPreparationTask).withPoolInfo(poolInformation)
            .withConstraints(jobConstraints);

    client.jobOperations().createJob(param);

    // We may createTasks with multi-threads if we have many tasks.        
    ArrayList<BatchClientBehavior> listBehaviors = new ArrayList<>();
    listBehaviors.add(new BatchClientParallelOptions(20));

    Logger.log(listener, "Job with Id %s is created, now to add tasks...", jobId);
    client.taskOperations().createTasks(jobId, taskList, listBehaviors);
    Logger.log(listener, "%d tasks are added to job %s.", taskList.size(), jobId);
}

From source file:com.microsoft.azurebatch.jenkins.azurebatch.JobGenerator.java

License:Open Source License

private TaskAddParameter getTaskOnePerTaskType(TaskDefinition taskDefinition, String taskPostProcessFileName)
        throws IOException, URISyntaxException, StorageException, IllegalArgumentException,
        InterruptedException, InvalidKeyException {
    List<String> resultFilePatterns = projectConfigHelper.getTestConfigs().getResultFilePatterns();
    String taskId = taskDefinition.getTaskId();

    TaskAddParameter taskAddParam = new TaskAddParameter();
    taskAddParam.withId(taskId).withDisplayName(taskDefinition.getName());

    List<String> commandLineList = new ArrayList<>();

    for (String command : taskDefinition.getCommands()) {
        commandLineList.add(String.format("cmd /c %s >> task_stdout.txt 2>>task_stderr.txt", command));
    }/*from  ww w  . j av  a  2s  .co m*/

    // Copy results to a temp folder
    List<String> resultFilePatternList = new ArrayList<>(resultFilePatterns);

    // Copy all result files to randomUUID_ResultFolder\taskId\ folder.
    String tempResultFolderName = "tempResults" + UUID.randomUUID().toString().replace("-", "").substring(0, 6);
    commandLineList.add(String.format("mkdir %s\\%s", tempResultFolderName, taskId));
    for (String resultFilePattern : resultFilePatternList) {
        // Copy results and ignore failures
        commandLineList.add(
                String.format("copy %s %s\\%s /Y 2>null", resultFilePattern, tempResultFolderName, taskId));
    }

    // Call taskPostProcessFile
    // SAS key may contain '%', replace it with '%%' before passing to .cmd script.
    commandLineList.add(String.format("cmd /c %s %s %s %s \"%s\" %s", taskPostProcessFileName, jobId, taskId,
            storageAccountInfo.getAccountName(), containerSasKey.replace("%", "%%"), tempResultFolderName));

    String workPathCmd = scriptTempFolder + File.separator + taskId + ".cmd";
    Path p = Paths.get(workPathCmd);
    if (Files.exists(p)) {
        Files.delete(p);
    }

    // Generate the task command line at run time based on the dll
    try (Writer writer = new OutputStreamWriter(new FileOutputStream(new File(workPathCmd), false),
            java.nio.charset.Charset.defaultCharset())) {
        for (String line : commandLineList) {
            writer.write(line);
            writer.write(System.getProperty("line.separator"));
        }
    } catch (IOException e) {
        Logger.log(listener, "Task command file generation failed");
        Logger.log(listener, e.getMessage());
        throw e;
    }

    TaskConstraints taskConstraints = new TaskConstraints();
    taskConstraints.withMaxWallClockTime(Period.minutes(taskDefinition.getTimeoutInMins()));

    taskAddParam.withCommandLine(
            String.format("cmd /c copy %s\\scripts\\%s.cmd && cmd /c copy %s\\scripts\\%s && %s.cmd",
                    "%AZ_BATCH_NODE_SHARED_DIR%\\%AZ_BATCH_JOB_ID%", taskId,
                    "%AZ_BATCH_NODE_SHARED_DIR%\\%AZ_BATCH_JOB_ID%", taskPostProcessFileName, taskId));
    taskAddParam.withConstraints(taskConstraints);

    return taskAddParam;
}

From source file:com.netflix.iep.config.Strings.java

License:Apache License

private static Period parseAtPeriod(String amt, String unit) {
    int v = Integer.valueOf(amt);
    if (unit.equals("s") || unit.equals("second") || unit.equals("seconds"))
        return Period.seconds(v);
    if (unit.equals("m") || unit.equals("min") || unit.equals("minute") || unit.equals("minutes"))
        return Period.minutes(v);
    if (unit.equals("h") || unit.equals("hour") || unit.equals("hours"))
        return Period.hours(v);
    if (unit.equals("d") || unit.equals("day") || unit.equals("days"))
        return Period.days(v);
    if (unit.equals("w") || unit.equals("wk") || unit.equals("week") || unit.equals("weeks"))
        return Period.weeks(v);
    if (unit.equals("month") || unit.equals("months"))
        return Period.months(v);
    if (unit.equals("y") || unit.equals("year") || unit.equals("years"))
        return Period.years(v);
    throw new IllegalArgumentException("unknown unit " + unit);
}

From source file:com.ning.metrics.collector.endpoint.EventEndPointStats.java

License:Apache License

public EventEndPointStats(int rateWindowSizeMinutes) {
    this.rateWindowSizeMinutes = rateWindowSizeMinutes;
    eventParseRate = new EventRate(Period.minutes(rateWindowSizeMinutes));
    successfulEventParseRate = new EventRate(Period.minutes(rateWindowSizeMinutes));
    failedEventParseRate = new EventRate(Period.minutes(rateWindowSizeMinutes));
    filteredEventParseRate = new EventRate(Period.minutes(rateWindowSizeMinutes));
    rejectedEventRate = new EventRate(Period.minutes(rateWindowSizeMinutes));
}

From source file:com.ning.metrics.serialization.writer.DiskSpoolEventWriter.java

License:Apache License

public DiskSpoolEventWriter(EventHandler eventHandler, String spoolPath, boolean flushEnabled,
        long flushIntervalInSeconds, ScheduledExecutorService executor, SyncType syncType, int syncBatchSize,
        int rateWindowSizeMinutes) {
    this.eventHandler = eventHandler;
    this.rateWindowSizeMinutes = rateWindowSizeMinutes;
    this.syncType = syncType;
    this.syncBatchSize = syncBatchSize;
    this.spoolDirectory = new File(spoolPath);
    this.executor = executor;
    this.tmpSpoolDirectory = new File(spoolDirectory, "_tmp");
    this.quarantineDirectory = new File(spoolDirectory, "_quarantine");
    this.lockDirectory = new File(spoolDirectory, "_lock");
    this.flushEnabled = new AtomicBoolean(flushEnabled);
    this.flushIntervalInSeconds = new AtomicLong(flushIntervalInSeconds);

    writeRate = new EventRate(Period.minutes(rateWindowSizeMinutes));

    createSpoolDir(spoolDirectory);/*  ww  w .java2s  .  co m*/
    createSpoolDir(tmpSpoolDirectory);
    createSpoolDir(quarantineDirectory);
    createSpoolDir(lockDirectory);
    scheduleFlush();
    recoverFiles();
}

From source file:com.serotonin.m2m2.Common.java

License:Open Source License

public static Period getPeriod(int periodType, int periods) {
    switch (periodType) {
    case TimePeriods.MILLISECONDS:
        return Period.millis(periods);
    case TimePeriods.SECONDS:
        return Period.seconds(periods);
    case TimePeriods.MINUTES:
        return Period.minutes(periods);
    case TimePeriods.HOURS:
        return Period.hours(periods);
    case TimePeriods.DAYS:
        return Period.days(periods);
    case TimePeriods.WEEKS:
        return Period.weeks(periods);
    case TimePeriods.MONTHS:
        return Period.months(periods);
    case TimePeriods.YEARS:
        return Period.years(periods);
    default://from   www  . java2s  . c om
        throw new ShouldNeverHappenException("Unsupported time period: " + periodType);
    }
}