Last active
February 27, 2017 10:54
-
-
Save syhily/ac8bc40f13ff82dc359d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package com.oneapm.research.alert.utils; | |
| import lombok.Getter; | |
| import java.util.concurrent.TimeUnit; | |
| public class Timer { | |
| private static final long INITIAL_TIME = 0L; | |
| @Getter | |
| private long startTime = System.currentTimeMillis(); | |
| @Getter | |
| private long endTime = INITIAL_TIME; | |
| private Timer() { | |
| // no construct | |
| } | |
| public static Timer start() { | |
| return new Timer(); | |
| } | |
| public long stop() { | |
| endTime = System.currentTimeMillis(); | |
| return endTime; | |
| } | |
| public long getTotalTime() { | |
| if (endTime == INITIAL_TIME) { | |
| stop(); | |
| } | |
| return endTime - startTime; | |
| } | |
| public boolean isExpired(long expiredTime, TimeUnit timeUnit) { | |
| stop(); | |
| return getTotalTime() > timeUnit.toMillis(expiredTime); | |
| } | |
| public boolean isNotExpired(long expiredTime, TimeUnit timeUnit) { | |
| return !isExpired(expiredTime, timeUnit); | |
| } | |
| @Override | |
| public String toString() { | |
| if (endTime == INITIAL_TIME) { | |
| stop(); | |
| } | |
| return String.format("%d", getTotalTime()); | |
| } | |
| public String formattedStartTime() { | |
| return formatTimestamp(startTime); | |
| } | |
| public String formattedEndTime() { | |
| if (endTime == INITIAL_TIME) { | |
| stop(); | |
| } | |
| return formatTimestamp(endTime); | |
| } | |
| private String formatTimestamp(long timestamp) { | |
| return String.format("%1$tY-%1$tb-%1$td %1$tT %tZ", timestamp); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment