---
title: "Spring定时器StopWatch"
author: "iTommy"
date: "2017-02-04T20:52:10Z"
tags: []
categories: ["编程语言"]
slug: "spring-stopwatch"
draft: false
lastmod: "2017-02-04T20:51:04Z"
id: 2355440
url: "https://itommy.iteye.com/blog/2355440"
---

简单总结一句，Spring提供的计时器StopWatch对于秒、毫秒为单位方便计时的程序，尤其是单线程、顺序执行程序的时间特性的统计输出支持比较好。也就是说假如我们手里面有几个在顺序上前后执行的几个任务，而且我们比较关心几个任务分别执行的时间占用状况，希望能够形成一个不太复杂的日志输出，StopWatch提供了这样的功能。而且Spring的StopWatch基本上也就是仅仅为了这样的功能而实现。

 

实际中用到的代码：

```
public void run() {
	LOGGER.info("[" + taskName + "]开始执行");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start(taskName);
        try {
            doTask();
        } catch (Exception e) {
            LOGGER.error("[" + taskName + "]执行失败", e);
        } finally {
            stopWatch.stop();
            LOGGER.info("[" + taskName + "]执行结束,耗时:" + stopWatch.getTotalTimeMillis() + "毫秒");
        }
}
```

 

另外，还可以使用一些其他的方法：

```
import org.springframework.util.StopWatch;  
  
public class StopWatchDemo {  
  
    /** 
     * @param args 
     * @throws InterruptedException 
     */  
    public static void main(String[] args) throws InterruptedException {  
        // TODO Auto-generated method stub  
        StopWatch clock = new StopWatch();  
        clock.start("TaskOneName");  
        Thread.sleep(1000 * 3);// 任务一模拟休眠3秒钟  
        clock.stop();  
        clock.start("TaskTwoName");  
        Thread.sleep(1000 * 10);// 任务一模拟休眠10秒钟  
        clock.stop();  
        clock.start("TaskThreeName");  
        Thread.sleep(1000 * 10);// 任务一模拟休眠10秒钟  
        clock.stop();  
  
        System.out.println(clock.prettyPrint());  
    }  
  
} 
```

 

控制台输出如下：  
StopWatch '': running time (millis) = 22926  
\-----------------------------------------  
ms     %     Task name  
\-----------------------------------------  
02990  013%  TaskOneName  
09968  043%  TaskTwoName  
09968  043%  TaskThreeName

 

 

http://blog.csdn.net/ioe\_gaoyong/article/details/22788789