Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Last active May 16, 2018 21:57
Show Gist options
  • Save RustyKnight/452e13b193543f3eb6db035990b526cb to your computer and use it in GitHub Desktop.
Save RustyKnight/452e13b193543f3eb6db035990b526cb to your computer and use it in GitHub Desktop.
Simple "counter" for duration based counting (ie timeouts)
import java.time.Duration;
import java.time.LocalDateTime;
/*
I seem to need to provide a lot of examples on stack overflow which are either performing a forward, backward or needs
to calculate the percentage of progression for a period of time.
Since most of this functionality can easily be distilled, I wrote myself a simple "counter" class.
It takes a Duration and, when started, can calculate the amount of time it's been running (up to the specified Duration),
the amount of remaining time (down to 0) and the percentage of the time used (up to 1.0)
*/
public class Counter {
private Duration duration;
private LocalDateTime startedAt;
public Counter(Duration length) {
this.duration = length;
}
public Duration getDuration() {
return duration;
}
public boolean isRunning() {
return startedAt != null;
}
public void start() {
startedAt = LocalDateTime.now();
}
public void stop() {
startedAt = null;
}
public boolean isCompleted() {
return getRunningDuration().equals(getDuration());
}
public Duration getRunningDuration() {
if (startedAt == null) {
return null;
}
Duration duration = Duration.between(startedAt, LocalDateTime.now());
if (duration.compareTo(getDuration()) > 0) {
duration = getDuration();
}
return duration;
}
public Double getProgress() {
if (startedAt == null) {
return null;
}
Duration duration = getRunningDuration();
return Math.min(1.0, (double) duration.toMillis() / this.duration.toMillis());
}
public Duration getRemainingDuration() {
if (startedAt == null) {
return null;
}
Duration length = getDuration();
Duration time = getRunningDuration();
LocalDateTime endTime = startedAt.plus(length);
LocalDateTime runTime = startedAt.plus(time);
Duration duration = Duration.between(runTime, endTime);
if (duration.isNegative()) {
duration = Duration.ZERO;
}
return duration;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment