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


Java DurationFormatUtils类代码示例

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


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

示例1: check

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
private static void check() {
	LogUtils.infof("Checking dead shards...");
	for(ShadbotShard shardStatus : SHARDS_MAP.values()) {
		try {
			// Ignore shards with less than 100 guilds
			if(shardStatus.getShard().getGuilds().size() < 100) {
				continue;
			}
			long lastEventTime = TimeUtils.getMillisUntil(shardStatus.getLastEventTime());
			long lastMessageTime = TimeUtils.getMillisUntil(shardStatus.getLastMessageTime());
			if(lastEventTime > TimeUnit.SECONDS.toMillis(SHARD_TIMEOUT) || lastMessageTime > TimeUnit.SECONDS.toMillis(SHARD_TIMEOUT)) {
				LogUtils.infof(String.format("Restarting shard %d (Response time: %d ms | Last event: %s ago | Last message: %s ago)",
						shardStatus.getID(),
						shardStatus.getShard().getResponseTime(),
						DurationFormatUtils.formatDurationWords(lastEventTime, true, true),
						DurationFormatUtils.formatDurationWords(lastMessageTime, true, true)));
				shardStatus.restart();
			}
		} catch (Exception err) {
			LogUtils.errorf(err, "An error occurred while restarting a shard.");
		}
	}
	LogUtils.infof("Dead shards checked.");
}
 
开发者ID:Shadorc,项目名称:Shadbot,代码行数:25,代码来源:ShardManager.java

示例2: onPlayerPreFactionJoin

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerPreFactionJoin(PlayerJoinFactionEvent event) {
    Faction faction = event.getFaction();
    Optional<Player> optionalPlayer = event.getPlayer();
    if (faction instanceof PlayerFaction && optionalPlayer.isPresent()) {
        Player player = optionalPlayer.get();
        PlayerFaction playerFaction = (PlayerFaction) faction;

        if (!plugin.getEotwHandler().isEndOfTheWorld() && playerFaction.getRegenStatus() == RegenStatus.PAUSED) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + "You cannot join factions that are not regenerating DTR.");
            return;
        }

        long difference = (plugin.getUserManager().getUser(player.getUniqueId()).getLastFactionLeaveMillis() - System.currentTimeMillis()) + FACTION_JOIN_WAIT_MILLIS;
        if (difference > 0L && !player.hasPermission("hcf.faction.argument.staff.forcejoin")) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + "You cannot join factions after just leaving within " + FACTION_JOIN_WAIT_WORDS + ". " + "You gotta wait another "
                    + DurationFormatUtils.formatDurationWords(difference, true, true) + '.');
        }
        UUID uuid = player.getUniqueId();
        HCF.getInstance().getUserManager().users.putIfAbsent(uuid, new FactionUser(uuid));
    }
}
 
开发者ID:funkemunky,项目名称:HCFCore,代码行数:25,代码来源:FactionListener.java

示例3: onCommand

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    EventTimer eventTimer = plugin.getTimerManager().getEventTimer();

    if (eventTimer.getRemaining() <= 0L) {
        sender.sendMessage(ChatColor.RED + "There is not a running event.");
        return true;
    }

    EventFaction eventFaction = eventTimer.getEventFaction();
    sender.sendMessage(ChatColor.YELLOW + "Up-time of " + eventTimer.getName() + " timer"
            + (eventFaction == null ? "" : ": " + ChatColor.BLUE + '(' + eventFaction.getDisplayName(sender) + ChatColor.BLUE + ')') + ChatColor.YELLOW + " is " + ChatColor.GRAY
            + DurationFormatUtils.formatDurationWords(eventTimer.getUptime(), true, true) + ChatColor.YELLOW + ", started at " + ChatColor.GOLD
            + DateTimeFormats.HR_MIN_AMPM_TIMEZONE.format(eventTimer.getStartStamp()) + ChatColor.YELLOW + '.');

    return true;
}
 
开发者ID:funkemunky,项目名称:HCFCore,代码行数:18,代码来源:EventUptimeArgument.java

示例4: handleWinner

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
/**
 * Handles the winner for this event.
 *
 * @param winner
 *            the {@link Player} that won
 */
public void handleWinner(Player winner) {
    if (this.eventFaction == null)
        return;

    PlayerFaction playerFaction = plugin.getFactionManager().getPlayerFaction(winner);
    Bukkit.broadcastMessage(ChatColor.GOLD + "[" + "WIN" + "] " + ChatColor.RED + winner.getName() + ChatColor.AQUA
            + ChatColor.YELLOW + " has captured " + ChatColor.RED + this.eventFaction.getName()
            + ChatColor.YELLOW + " after " + ChatColor.RED + DurationFormatUtils.formatDurationWords(getUptime(), true, true) + " of up-time" + ChatColor.YELLOW + '.');

    EventType eventType = this.eventFaction.getEventType();
    World world = winner.getWorld();
    Location location = winner.getLocation();
    EventKey eventKey = plugin.getKeyManager().getEventKey();
    Collection<Inventory> inventories = eventKey.getInventories(eventType);
    ItemStack keyStack = eventKey.getItemStack(new EventKey.EventKeyData(eventType, inventories.isEmpty() ? 1 : plugin.getRandom().nextInt(inventories.size()) + 1));
    Map<Integer, ItemStack> excess = winner.getInventory().addItem(keyStack, EventSignListener.getEventSign(eventFaction.getName(), winner.getName()));
    for (ItemStack entry : excess.values()) {
        world.dropItemNaturally(location, entry);
    }

    this.clearCooldown(); // must always be cooled last as this nulls some variables.
}
 
开发者ID:funkemunky,项目名称:HCFCore,代码行数:29,代码来源:EventTimer.java

示例5: onPlayerInteract

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerInteract(PlayerInteractEvent event) {
    if (event.hasItem() && event.getItem().getType() == Material.GOLDEN_CARROT) {
        Player player = event.getPlayer();
        if (plugin.getPvpClassManager().getEquippedClass(player) == this) {
            long timestamp = cooldowns.get(player.getUniqueId());
            long millis = System.currentTimeMillis();
            long remaining = timestamp == cooldowns.getNoEntryValue() ? 0L : timestamp - millis;
            if (remaining > 0L) {
                player.sendMessage(ChatColor.RED + "Cooldown still for " + DurationFormatUtils.formatDurationWords(remaining, true, true) + ".");
                return;
            }

            cooldowns.put(player.getUniqueId(), millis + 15000L);
            plugin.getEffectRestorer().setRestoreEffect(player, new PotionEffect(PotionEffectType.SPEED, 100, 4));
            plugin.getEffectRestorer().setRestoreEffect(player, new PotionEffect(PotionEffectType.INVISIBILITY, 100, 0));
        }
    }
}
 
开发者ID:funkemunky,项目名称:HCFCore,代码行数:20,代码来源:AssassinClass.java

示例6: onCommand

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
    if(!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "This command is only executable by players.");
        return true;
    }
    final Player player = (Player) sender;
    if(player.getWorld().getEnvironment() != World.Environment.NORMAL) {
        sender.sendMessage(ChatColor.RED + "You can only use this command from the overworld.");
        return true;
    }
    if(plugin.getFactionManager().getFactionAt(((Player) sender).getLocation()) instanceof SpawnFaction){
        sender.sendMessage(ChatColor.RED + "You cannot " + label + " " + this.getName() + " inside of Spawn");
        return true;
    }
    final StuckTimer stuckTimer = this.plugin.getTimerManager().getStuckTimer();
    if(!stuckTimer.setCooldown(player, player.getUniqueId())) {
        sender.sendMessage(ChatColor.YELLOW + "Your " + stuckTimer.getDisplayName() + ChatColor.YELLOW + " timer has a remaining " + ChatColor.LIGHT_PURPLE + DurationFormatUtils.formatDurationWords(stuckTimer.getRemaining(player), true, true)+ChatColor.YELLOW + '.');
        return true;
    }
    sender.sendMessage(ChatColor.YELLOW + stuckTimer.getDisplayName() + ChatColor.YELLOW + " timer has started. " + "\nTeleportation will commence in " + ChatColor.LIGHT_PURPLE + DurationFormatter.getRemaining(stuckTimer.getRemaining(player), true, false) + ChatColor.YELLOW + ". " + "\nThis will cancel if you move more than " + 5 + " blocks.");
    return true;
}
 
开发者ID:funkemunky,项目名称:HCFCore,代码行数:23,代码来源:FactionStuckArgument.java

示例7: onCommand

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (args.length < 2) {
        sender.sendMessage(ChatColor.RED + "Usage: " + getUsage(label));
        return true;
    }

    long duration = JavaUtils.parse(args[1]);

    if (duration == -1L) {
        sender.sendMessage(ChatColor.RED + "Invalid duration, use the correct format: 10m 1s");
        return true;
    }

    SettingsYML.DEFAULT_DEATHBAN_DURATION = duration;
    Command.broadcastCommandMessage(sender, ChatColor.RED + "Base death-ban time set to " + DurationFormatUtils.formatDurationWords(duration, true, true) + " (not including multipliers, etc).");

    return true;
}
 
开发者ID:funkemunky,项目名称:HCFCore,代码行数:20,代码来源:LivesSetDeathbanTimeArgument.java

示例8: onPlayerPreFactionJoin

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerPreFactionJoin(PlayerJoinFactionEvent event) {
    Faction faction = event.getFaction();
    Optional<Player> optionalPlayer = event.getPlayer();
    if (faction instanceof PlayerFaction && optionalPlayer.isPresent()) {
        Player player = optionalPlayer.get();
        PlayerFaction playerFaction = (PlayerFaction) faction;

        if (!plugin.getEotwHandler().isEndOfTheWorld() && playerFaction.getRegenStatus() == RegenStatus.PAUSED) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + "You cannot join factions that are not regenerating DTR.");
            return;
        }

        long difference = (plugin.getUserManager().getUser(player.getUniqueId()).getLastFactionLeaveMillis() - System.currentTimeMillis()) + FACTION_JOIN_WAIT_MILLIS;
        if (difference > 0L && !player.hasPermission("hcf.faction.argument.staff.forcejoin")) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + "You cannot join factions after just leaving within " + FACTION_JOIN_WAIT_WORDS + ". " + "You gotta wait another "
                    + DurationFormatUtils.formatDurationWords(difference, true, true) + '.');
        }
    }
}
 
开发者ID:funkemunky,项目名称:HCFCore,代码行数:23,代码来源:FactionListener.java

示例9: writeDuration

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
/**
 * Write a duration using the "HH:mm:ss" format and in millisecond format, so 2 strings are added in the CSV output.
 * <code>null</code> management is performed there.
 * Empty {@link String} is written with <code>null</code> duration.
 * 
 * @param writer
 *            The target output.
 * @param duration
 *            The duration to write, in milliseconds.
 */
protected void writeDuration(final Writer writer, final Long duration) throws IOException {
	if (duration == null) {
		// null duration
		writer.write(";;");
	} else {
		writer.write(';');
		if (duration < 0) {
			// Add the sign before the HMS value
			writer.write('-');
		}
		writer.write(DurationFormatUtils.formatDuration(Math.abs(duration), "HH:mm:ss"));
		writer.write(';');
		writer.write(String.valueOf(duration));
	}
}
 
开发者ID:ligoj,项目名称:plugin-bt-jira,代码行数:26,代码来源:AbstractCsvOutput.java

示例10: prepareRequestInCooldownMail

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
private void prepareRequestInCooldownMail(SingularityRequest request) {
  final List<SingularityEmailDestination> emailDestination = getDestination(request, SingularityEmailType.REQUEST_IN_COOLDOWN);

  if (emailDestination.isEmpty()) {
    LOG.debug("Not configured to send request cooldown mail for");
    return;
  }

  final Map<String, Object> templateProperties = Maps.newHashMap();
  populateRequestEmailProperties(templateProperties, request);

  final String subject = String.format("Request %s has entered system cooldown — Singularity", request.getId());

  templateProperties.put("numFailures", configuration.getCooldownAfterFailures());
  templateProperties.put("cooldownDelayFormat", DurationFormatUtils.formatDurationHMS(TimeUnit.SECONDS.toMillis(configuration.getCooldownMinScheduleSeconds())));
  templateProperties.put("cooldownExpiresFormat", DurationFormatUtils.formatDurationHMS(TimeUnit.MINUTES.toMillis(configuration.getCooldownExpiresAfterMinutes())));

  final String body = Jade4J.render(requestInCooldownTemplate, templateProperties);

  queueMail(emailDestination, request, SingularityEmailType.REQUEST_IN_COOLDOWN, Optional.<String> absent(), subject, body);
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:22,代码来源:SingularityMailer.java

示例11: isDeployOverdue

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
private boolean isDeployOverdue(SingularityPendingDeploy pendingDeploy, Optional<SingularityDeploy> deploy) {
  if (!deploy.isPresent()) {
    LOG.warn("Can't determine if deploy {} is overdue because it was missing", pendingDeploy);
    return false;
  }

  if (pendingDeploy.getDeployProgress().isPresent() && pendingDeploy.getDeployProgress().get().isStepComplete()) {
    return false;
  }

  final long startTime = getStartTime(pendingDeploy);

  final long deployDuration = System.currentTimeMillis() - startTime;

  final long allowedTime = getAllowedMillis(deploy.get());

  if (deployDuration > allowedTime) {
    LOG.warn("Deploy {} is overdue (duration: {}), allowed: {}", pendingDeploy, DurationFormatUtils.formatDurationHMS(deployDuration), DurationFormatUtils.formatDurationHMS(allowedTime));

    return true;
  } else {
    LOG.trace("Deploy {} is not yet overdue (duration: {}), allowed: {}", pendingDeploy, DurationFormatUtils.formatDurationHMS(deployDuration), DurationFormatUtils.formatDurationHMS(allowedTime));

    return false;
  }
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:27,代码来源:SingularityDeployChecker.java

示例12: enqueueHealthcheckWithDelay

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
private ScheduledFuture<?> enqueueHealthcheckWithDelay(final SingularityTask task, long delaySeconds) {
  LOG.trace("Enqueuing a healthcheck for task {} with delay {}", task.getTaskId(), DurationFormatUtils.formatDurationHMS(TimeUnit.SECONDS.toMillis(delaySeconds)));

  return executorService.schedule(new Runnable() {

    @Override
    public void run() {
      try {
        asyncHealthcheck(task);
      } catch (Throwable t) {
        LOG.error("Uncaught throwable in async healthcheck", t);
        exceptionNotifier.notify(t, ImmutableMap.of("taskId", task.getTaskId().toString()));

        reEnqueueOrAbort(task);
      }
    }

  }, delaySeconds, TimeUnit.SECONDS);
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:20,代码来源:SingularityHealthchecker.java

示例13: player

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
@RequestMapping("/t/{tempo}/m/{mode}/players/{name}")
public ModelAndView player(@PathVariable("tempo") Tempo tempo, @PathVariable("mode") String mode, @PathVariable("name") String name) {
    GameMode gameMode = gameModes.find(GameModeId.of(mode)).orElseThrow(NotAvailableException::new);

    PlayerStats playerStats = playerStatsRepository.playerStatsOps(tempo).playerStats(gameMode.getId(), name).orElseGet(() -> PlayerStats.of(gameMode.getId(), name));
    Map<Badge, BadgeLevel> badgeLevels = badgeRepository.badgeOps(tempo).badgeLevels(gameMode.getId(), name);

    Function<Long, String> x = m -> DurationFormatUtils.formatDurationWords(m, true, false);

    return
        new ModelAndView("player")
            .addObject("tempo", tempo)
            .addObject("name", name)
            .addObject("gameMode", gameMode)
            .addObject("gameModes", gameModes)
            .addObject("stats", playerStats)
            .addObject("badges", gameMode.getBadges())
            .addObject("badgeLevels", badgeLevels)
            .addObject("durationFormatter", x)
        ;
}
 
开发者ID:nosceon,项目名称:tenorite,代码行数:22,代码来源:TempoController.java

示例14: appendDeadlineInformation

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
private void appendDeadlineInformation(StringBuilder sb, WorkItemEvent event) {
	WorkItemType workItem = event.getWorkItem();
	if (!isDone(event) && workItem.getDeadline() != null) {
		XMLGregorianCalendar deadline = workItem.getDeadline();
		long before = XmlTypeConverter.toMillis(deadline) - System.currentTimeMillis();
		long beforeRounded = Math.round((double) before / 60000.0) * 60000L;
		String beforeWords = DurationFormatUtils.formatDurationWords(Math.abs(beforeRounded), true, true);
		String beforePhrase;
		if (beforeRounded > 0) {
			beforePhrase = " (in " + beforeWords + ")";
		} else if (beforeRounded < 0) {
			beforePhrase = " (" + beforeWords + " ago)";
		} else {
			beforePhrase = "";
		}
		sb.append("Deadline: ").append(textFormatter.formatDateTime(deadline)).append(beforePhrase).append("\n");
		sb.append("\n");
	}
}
 
开发者ID:Pardus-Engerek,项目名称:engerek,代码行数:20,代码来源:SimpleWorkflowNotifier.java

示例15: testMini

import org.apache.commons.lang3.time.DurationFormatUtils; //导入依赖的package包/类
@Test
public void testMini() throws Exception {
    String content = IOUtils.toString(getClass().getResourceAsStream("/json/album-mini.json"));
    String id = String.valueOf(System.currentTimeMillis());
    String type = "Album";
    List<JsonObjectDescriptor> descriptors = new ArrayList<>();
    descriptors.add(new JsonObjectDescriptor(type, Arrays.asList("id", "type"), "type"));
    JsonDocument jsonDocument = new JsonDocument(id, type, content, JsonMappingStrategy.DOMAIN_DRIVEN, descriptors);
    DomainDrivenJsonTransformer transformer = new DomainDrivenJsonTransformer();
    long start = System.currentTimeMillis();
    String transformedSet = transformer.transform(jsonDocument);
    long end = System.currentTimeMillis();
    System.out.println("---------RESULT---------");
    System.out.println(transformedSet);
    System.out.println("Time elapsed: " + DurationFormatUtils.formatDurationHMS(end - start));
}
 
开发者ID:larusba,项目名称:neo4j-json-loader,代码行数:17,代码来源:DomainBasedAmbumMiniJsonTransformerTest.java


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