0
# Duration Utilities
1
2
Duration management capabilities for parsing and manipulating duration values with support for various time units and conversion to standard Java types.
3
4
## Duration Class
5
6
The `Duration` class provides helper methods for parsing human-readable duration values into a thread-safe, immutable representation.
7
8
### Static Factory Methods
9
10
Create Duration instances for specific time units:
11
12
```java { .api }
13
public static Duration nanoseconds(long count);
14
public static Duration microseconds(long count);
15
public static Duration milliseconds(long count);
16
public static Duration seconds(long count);
17
public static Duration minutes(long count);
18
public static Duration hours(long count);
19
public static Duration days(long count);
20
```
21
22
**Parameters:**
23
- `count` - The number of time units
24
25
**Returns:** A new Duration instance representing the specified time period
26
27
### Parsing Methods
28
29
Parse human-readable strings into Duration objects:
30
31
```java { .api }
32
public static Duration parse(String duration);
33
```
34
35
**Parameters:**
36
- `duration` - String representation like "30 seconds", "5 minutes", "2 hours"
37
38
**Returns:** A valid Duration representing the parsed input string
39
40
**Supported Formats:**
41
- Full unit names: "30 seconds", "5 minutes", "2 hours", "1 day"
42
- Abbreviated forms: "30s", "5m", "2h", "1d"
43
- Plural and singular: "1 second", "2 seconds", "1 minute", "5 minutes"
44
- Case variations: "SECONDS", "Minutes", "ms"
45
46
**Supported Units:**
47
- `ns`, `nanosecond`, `nanoseconds` - Nanoseconds
48
- `us`, `microsecond`, `microseconds` - Microseconds
49
- `ms`, `millisecond`, `milliseconds` - Milliseconds
50
- `s`, `second`, `seconds` - Seconds
51
- `m`, `min`, `mins`, `minute`, `minutes` - Minutes
52
- `h`, `hour`, `hours` - Hours
53
- `d`, `day`, `days` - Days
54
55
**Throws:**
56
- `IllegalArgumentException` - If the input cannot be parsed or contains invalid time units
57
58
### Instance Methods
59
60
Access duration properties:
61
62
```java { .api }
63
public long getQuantity();
64
public TimeUnit getUnit();
65
```
66
67
Convert to specific time units:
68
69
```java { .api }
70
public long toNanoseconds();
71
public long toMicroseconds();
72
public long toMilliseconds();
73
public long toSeconds();
74
public long toMinutes();
75
public long toHours();
76
public long toDays();
77
```
78
79
Convert to Java standard library Duration:
80
81
```java { .api }
82
public java.time.Duration toJavaDuration();
83
```
84
85
Standard object methods:
86
87
```java { .api }
88
public boolean equals(Object obj);
89
public int hashCode();
90
public String toString();
91
public int compareTo(Duration other);
92
```
93
94
## Usage Examples
95
96
### Basic Creation
97
98
```java
99
// Create using factory methods
100
Duration fiveSeconds = Duration.seconds(5);
101
Duration tenMinutes = Duration.minutes(10);
102
Duration oneHour = Duration.hours(1);
103
Duration threedays = Duration.days(3);
104
105
// Get quantity and unit
106
long quantity = fiveSeconds.getQuantity(); // 5
107
TimeUnit unit = fiveSeconds.getUnit(); // TimeUnit.SECONDS
108
```
109
110
### Parsing Examples
111
112
```java
113
// Parse various formats
114
Duration timeout = Duration.parse("30 seconds");
115
Duration interval = Duration.parse("5 minutes");
116
Duration delay = Duration.parse("2 hours");
117
Duration period = Duration.parse("1 day");
118
119
// Abbreviated forms
120
Duration shortTimeout = Duration.parse("30s");
121
Duration shortInterval = Duration.parse("5m");
122
Duration shortDelay = Duration.parse("2h");
123
Duration shortPeriod = Duration.parse("1d");
124
125
// Singular and plural forms
126
Duration oneSecond = Duration.parse("1 second");
127
Duration manySeconds = Duration.parse("30 seconds");
128
Duration oneMinute = Duration.parse("1 minute");
129
Duration manyMinutes = Duration.parse("10 minutes");
130
131
// Different cases work
132
Duration caseInsensitive = Duration.parse("30 SECONDS");
133
```
134
135
### Unit Conversion
136
137
```java
138
Duration original = Duration.parse("2 hours");
139
140
// Convert to different units
141
long nanoseconds = original.toNanoseconds(); // 7,200,000,000,000
142
long microseconds = original.toMicroseconds(); // 7,200,000,000
143
long milliseconds = original.toMilliseconds(); // 7,200,000
144
long seconds = original.toSeconds(); // 7,200
145
long minutes = original.toMinutes(); // 120
146
long hours = original.toHours(); // 2
147
long days = original.toDays(); // 0 (truncated)
148
```
149
150
### Java Integration
151
152
```java
153
// Convert to java.time.Duration for integration with modern Java APIs
154
Duration dropwizardDuration = Duration.parse("30 seconds");
155
java.time.Duration javaDuration = dropwizardDuration.toJavaDuration();
156
157
// Use with modern Java APIs
158
CompletableFuture.delayedExecutor(javaDuration.toMillis(), TimeUnit.MILLISECONDS);
159
160
// Convert back from java.time.Duration if needed
161
java.time.Duration javaTimeout = java.time.Duration.ofMinutes(5);
162
Duration dropwizardTimeout = Duration.milliseconds(javaTimeout.toMillis());
163
```
164
165
### Comparison and Sorting
166
167
```java
168
Duration short = Duration.seconds(30);
169
Duration long = Duration.minutes(2);
170
171
// Comparison (compares based on nanosecond values)
172
int comparison = short.compareTo(long); // negative (30s < 2min)
173
174
// Equality (compares quantity and unit exactly)
175
Duration seconds30a = Duration.seconds(30);
176
Duration seconds30b = Duration.seconds(30);
177
boolean equal = seconds30a.equals(seconds30b); // true
178
179
// Note: Different units with same time value are NOT equal
180
Duration millis30000 = Duration.milliseconds(30000);
181
Duration seconds30 = Duration.seconds(30);
182
boolean equalTime = millis30000.equals(seconds30); // false (different units)
183
boolean equalComparison = millis30000.compareTo(seconds30) == 0; // true (same time value)
184
```
185
186
### String Representation
187
188
```java
189
Duration duration = Duration.minutes(5);
190
String str = duration.toString(); // "5 minutes"
191
192
Duration singleUnit = Duration.minutes(1);
193
String singleStr = singleUnit.toString(); // "1 minute" (singular)
194
195
Duration multipleUnits = Duration.hours(2);
196
String multipleStr = multipleUnits.toString(); // "2 hours" (plural)
197
```
198
199
### Configuration Usage
200
201
Common pattern for configuration timeouts and intervals:
202
203
```java
204
// In configuration classes
205
public class DatabaseConfiguration {
206
private Duration connectionTimeout = Duration.seconds(30);
207
private Duration queryTimeout = Duration.minutes(5);
208
private Duration healthCheckInterval = Duration.seconds(10);
209
210
// Configuration parsing from YAML/properties
211
public void setConnectionTimeout(String timeout) {
212
this.connectionTimeout = Duration.parse(timeout);
213
}
214
215
// Usage in application code
216
public Connection getConnection() {
217
return dataSource.getConnection(connectionTimeout.toMilliseconds());
218
}
219
}
220
```
221
222
### Thread and Executor Usage
223
224
```java
225
// Use with thread operations
226
Duration sleepTime = Duration.parse("500ms");
227
Thread.sleep(sleepTime.toMilliseconds());
228
229
// Use with ScheduledExecutorService
230
Duration delay = Duration.parse("10 seconds");
231
Duration period = Duration.parse("1 minute");
232
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
233
executor.scheduleAtFixedRate(
234
task,
235
delay.toMilliseconds(),
236
period.toMilliseconds(),
237
TimeUnit.MILLISECONDS
238
);
239
```
240
241
## Error Handling
242
243
The parsing method throws `IllegalArgumentException` for invalid input:
244
245
```java
246
try {
247
Duration.parse("invalid duration"); // Throws IllegalArgumentException
248
} catch (IllegalArgumentException e) {
249
// Handle parsing error
250
}
251
252
try {
253
Duration.parse("30 invalid-unit"); // Throws IllegalArgumentException (unknown unit)
254
} catch (IllegalArgumentException e) {
255
// Handle unknown unit error
256
}
257
258
try {
259
Duration.parse("not-a-number seconds"); // Throws IllegalArgumentException (invalid number)
260
} catch (IllegalArgumentException e) {
261
// Handle number parsing error
262
}
263
```
264
265
## Integration with Java Time API
266
267
The Duration class provides seamless integration with Java's modern time APIs:
268
269
```java
270
// Convert to java.time.Duration for use with modern APIs
271
Duration dropwizardTimeout = Duration.parse("30 seconds");
272
java.time.Duration javaTimeout = dropwizardTimeout.toJavaDuration();
273
274
// Use with CompletableFuture
275
CompletableFuture<String> future = CompletableFuture
276
.supplyAsync(() -> performOperation())
277
.orTimeout(javaTimeout.toMillis(), TimeUnit.MILLISECONDS);
278
279
// Use with reactive streams (if using reactive libraries)
280
Flux.interval(javaTimeout).subscribe(tick -> performPeriodicTask());
281
```