Last active
June 12, 2018 03:55
-
-
Save RustyKnight/059b32e3fec457a1a69b605d7a713575 to your computer and use it in GitHub Desktop.
A simple concept of a reusable "stop watch" with pause/resume capabilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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