Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Last active June 12, 2018 03:55
Show Gist options
  • Save RustyKnight/059b32e3fec457a1a69b605d7a713575 to your computer and use it in GitHub Desktop.
Save RustyKnight/059b32e3fec457a1a69b605d7a713575 to your computer and use it in GitHub Desktop.
A simple concept of a reusable "stop watch" with pause/resume capabilities
import java.time.Duration;
import java.time.Instant;
public class StopWatch {
private Instant startTime;
private Duration totalRunTime = Duration.ZERO;
public StopWatch start() {
startTime = Instant.now();
return this;
}
public StopWatch stop() {
Duration runTime = Duration.between(startTime, Instant.now());
totalRunTime = totalRunTime.plus(runTime);
startTime = null;
return this;
}
public StopWatch pause() {
return stop();
}
public StopWatch resume() {
return start();
}
public StopWatch reset() {
stop();
totalRunTime = Duration.ZERO;
return this;
}
public boolean isRunning() {
return startTime != null;
}
public Duration getDuration() {
Duration currentDuration = Duration.ZERO;
currentDuration = currentDuration.plus(totalRunTime);
if (isRunning()) {
Duration runTime = Duration.between(startTime, LocalDateTime.now());
currentDuration = currentDuration.plus(runTime);
}
return currentDuration;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment