96SEO 2026-08-10 02:57 35
在 Java 8 引入的新时间 API 中,java.time.Duration 是专门用于处理基于时间的时间量的主要类。它提供了纳秒级别的精度、不可变且线程安全的特性,还有丰富的算术和转换方法。
常见痛点:

Duration 与 Period 时容易产生错误,导致日期计算不准确。.toXxx/.ofXxx 方法。
// 基本单位创建
Duration d30s = Duration.ofSeconds;// 30 秒
Duration d15m = Duration.ofMinutes;// 15 分钟
Duration d2h = Duration.ofHours;// 2 小时
Duration d500ms = Duration.ofMillis;// 500 毫秒
Duration d1ns = Duration.ofNanos;// 1 毫秒
// 组合创建
Duration complex = Duration.ofHours
.plusMinutes
.plusSeconds;// 1 小时 30 分钟 45 秒
// 基于 Instant
Instant start = Instant.now;Thread.sleep;Instant end = Instant.now;说起来,Duration elapsed = Duration.娱乐ween;说起来,// 基于 LocalDateTime
LocalDateTime meetingStart = LocalDateTime.of;LocalDateTime meetingEnd = LocalDateTime.of;Duration meetingDuration = Duration.娱乐ween;// 基于 LocalTime
LocalTime workStart = LocalTime.of;LocalTime workEnd = LocalTime.of;老实说,Duration workDuration = Duration.娱乐ween;
Duration pt20s = Duration.parse;// 20 秒
Duration pt15m = Duration.parse;// 15 分钟
Duration pt10h = Duration.parse;// 10 小时
Duration p2d = Duration.parse;话说回来,// 2 天
Duration pt1h30m= Duration.parse;// 1 小时30分钟
Duration d = Duration.ofHours.plusMinutes;// 2 小时30 分钟
// 转换为不同单位
long totalHours = d.toHours;// → 2
long totalMinutes = d.toMinutes;// →150
long totalSeconds = d.toSeconds;// →9_000
long totalMillis = d.toMillis;// →9_000_000
// 获取各部分
long hoursPart = d.toHoursPart;// →2
long minutesPart = d.toMinutesPart;// →30
long secondsPart = d.toSecondsPart;// →0
long nanosPart = d.toNanosPart;// →0
Duration base = Duration.ofHours;// 加法 & 减法
Duration afterAdd = base.plusHours.plusMinutes.plusSeconds;Duration afterSubtract= base.minusMinutes;// 缩放——注意除以零会抛异常
Duration doubled = base.multipliedBy;Duration halved = base.dividedBy;// 正负号处理
Duration negative = Duration.ofHours;Duration absolute = negative.abs;// →5 小时正数
Duration shortTask= Duration.ofMinutes;Duration longTask = Duration.ofHours;boolean isShorter = shortTask.compareTo <0; // true
boolean isZero = shortTask.isZero; // false
boolean isNegative = shortTask.isNegative; // false
boolean equal = shortTask.equals); // true
public class PerformanceMonitor {
public static T measureExecution(String taskName,Supplier task) {
Instant start = Instant.now;其实,try {
T result = task.get;log,按理说,return result;} catch {
log",start);throw e,}
}
private static void log {
Instant end = Instant.now;Duration elapsed= Duration.娱乐ween;System.out.printf("任务 '%s' 执行时间: %d 毫秒%n"。name,elapsed.toMillis);}
public static void main {
String r= measureExecution -> {
try { Thread.sleep;} catch {}
return "查询结果";}),}
}
public class TimeoutManager {
private final Duration timeout;private final Duration retryInterval;public TimeoutManager(Duration timeout,Duration retryInterval) {
this.timeout = timeout;this.retryInterval= retryInterval;}
public T executeWithTimeout
throws TimeoutException {
Instant deadline= Instant.now.plus;while .isBefore) {
try { return task.call;}
catch {
if .isAfter)
throw new TimeoutException;long waitMs=Math.min。Duration.娱乐ween(
Instant.now,deadline)
.toMillis);try { Thread.sleep;}
catch {
Thread.currentThread.interrupt;
throw new RuntimeException;}
}
}
throw new TimeoutException;}
}
// 使用示例:
TimeoutManager manager=new TimeoutManager(
Duration.ofSeconds,// 超时时间
Duration.ofSeconds);// 重试间隔
// manager.executeWithTimeout -> ... );
public class TimedCache {
private final Map cache=new ConcurrentHashMap<>;private final Duration defaultTtl;public TimedCache { this.defaultTtl=defaultTtl;}
public void put{ put;怎么说呢,}
public void put{
Instant expiry=Instant.now.plus;cache.put),}
public V get{
CacheEntry entry=cache.get;if return null;if.isAfter){
cache.remove;return null,老实说,}
return entry.value;}
/** 定期清理,可交给后台线程执行 */
public void cleanup{
Instant now=Instant.now;cache.entrySet.removeIf.expiry));}
private static class CacheEntry{
final V value;final Instant expiry;话说回来,CacheEntry{ this.value=v;this.expiry=e;}
}
}
Date/TimerTask** 会出现线程安全和精度问题。public class TaskScheduler { private final ScheduledExecutorService scheduler= Executors.newScheduledThreadPool.availableProcessors);public ScheduledFuture> scheduleWithFixedDelay(Runnable task,Duration initialDelay。Duration delay){ return scheduler.scheduleWithFixedDelay(task,initialDelay.toMillis,delay.toMillis,TimeUnit.MILLISECONDS);} public ScheduledFuture> scheduleAtFixedRate(Runnable task,Dimension initialDelay。Dimension period){ return scheduler.scheduleAtFixedRate(task,initialDelay.toMillis,period.toMillis,TimeUnit.MILLISECONDS);} /** 示例:每隔30秒执行一次健康检查 */ public void startMonitoring{ scheduleAtFixedRate(this::healthCheck。Duration.ofSeconds,Duration.ofSeconds);} private void healthCheck{ System.out.println);} }
public class RateLimiter { private final Duration refillInterval;private final int maxTokens;private int tokens;private Instant lastRefill;public RateLimiter{ this.refillInterval=refillInterval;this.maxTokens=maxTokens;this.tokens=maxTokens;this.lastRefill=Instant.now;} /** 尝试获取一个令牌 */ public synchronized boolean tryAcquire{ refillTokens;说起来,if{ tokens--;话说回来,return true;话说回来,} return false;} /** 尝试获取 n 个令牌 */ public synchronized boolean tryAcquire{ refillTokens;if{ tokens -= permits;话说回来,return true;其实,} return false;} /** 补充令牌 */ private void refillTokens{ Instant now=Instant.now;long intervals= Duration.娱乐ween.dividedBy;if{ tokens=Math.min(maxTokens,tokens+intervals);lastRefill=lastRefill.plus);} } /** 距离下次补充还有多少时间 */ public Duration getTimeUntilNextRefill{ return Duration.娱乐ween( Instant.now,lastRefill.plus);} } // 示例: RateLimiter limiter=new RateLimiter,10);if){ System.out.println;}else{ System.out.println.toMillis+" ms");}
`requestTimeout`、`cacheTtl`、`sessionLength` 等,让阅读者一眼看出含义。`Duration.ofMinutes` 而非构造函数,以免产生歧义。{@link java.time.Period}。再配合 {@link java.time.Duration}.Date/Calendar/Period混用:
LocalDate today = LocalDate.now;LocalDate nextMonth = today.plusMonths;// ✅ 正确,用 Period 或 plusMonths LocalDate wrong = today.plus);// ❌ 潜在跨月错误,建议改为 Period。<\/codе>
ZonedDateTime zStart=ZonedDateTime.now;ZonedDateTime zEnd =&zStart.plus);// ✅ 正确保留 Zone 信息。<\/codе>
try{ Duration huge=Duration.ofDays;话说回来,long days =huge.toDays;// ⚠️ May overflow. }catch{ // 捕获并处理溢出情况。} <\/codе>
{@link java.time.Duration},如配置文件中的超时时间可以提前解析一次再复用。按理说,《Java Durаtion》 在以下场景中是首选工具 :
掌握上述技巧后你将能够轻松应对各种时间敏感业务需求,让程序既可靠又高效。
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback