计时器,相比于 原生的 不会抛出任何异常
非常适合job类处理,计算每个过程数量及耗时
定义
@NotThreadSafe
public class TimerWatch extends StopWatch {
private final String watchName;
private Integer totalCount;
// 是否记录观察子任务
private boolean keepTaskList = true;
public void setKeepTaskList(boolean keepTaskList) {
super.setKeepTaskList(keepTaskList);
this.keepTaskList = keepTaskList;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public TimerWatch() {
super("");
this.watchName = "";
}
// 观察命名
public TimerWatch(String watchName) {
super(watchName);
this.watchName = watchName;
}
// 开启观察任务命名
@Override
public void start(String taskName) {
try {
if (isRunning()) {
super.stop();
}
super.start(taskName);
} catch (Exception e) {
}
}
@Override
public void start() {
try {
if (isRunning()) {
super.stop();
}
super.start("");
} catch (Exception e) {
}
}
// 结束观察
@Override
public void stop() {
try {
if (isRunning()) {
super.stop();
}
} catch (Exception e) {
}
}
public String prettyLog() {
StringBuilder sb = new StringBuilder("StopWatch");
if (watchName != null) {
sb.append(" watchName:").append(watchName);
}
if (totalCount != null) {
sb.append(" totalCount:").append(totalCount);
}
sb.append(" totalConst:").append(getTotalTimeMillis()).append("ms");
try {
if (keepTaskList) {
for (StopWatch.TaskInfo task : getTaskInfo()) {
long percent = Math.round(100.0 * task.getTimeMillis() / getTotalTimeMillis());
sb.append("; [").append(task.getTaskName()).append(" const:").append(task.getTimeMillis()).append("ms").append(" percent:").append(percent).append("% ]");
}
}
} catch (Exception e) {
}
return sb.toString();
}
}