View Javadoc

1   /* ======================================
2    * Copyright (c) 2004-2005 Achim Nierbeck
3    * All rights reserved.
4    *
5    * You may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *       http://www.gnu.org/licenses/lgpl.html
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   * ======================================
16   */
17  
18  /*
19   * StopWatch.java
20   * $Revision: 1.7 $
21   * Date 14.12.2005
22   * 
23   * $Author: nierbeck $ 
24   * $Date: 2006/02/03 22:33:04 $ 
25   * 
26   */
27  
28  package de.nierbeck.timeTrack;
29  
30  import java.util.Calendar;
31  import java.util.Date;
32  
33  import de.nierbeck.timeTrack.model.EntryType;
34  
35  /***
36   * StopWatch Class which runs as thread updateing the duration section
37   * 
38   * @author Achim
39   * 
40   * @see java.lang.Thread
41   */
42  public final class StopWatch extends Thread {
43  	/***
44  	 * Static field UPDATE_INTERVAL 
45  	 */
46  	public static final int UPDATE_INTERVAL = 60000; // one minute
47  
48  	private transient final TimeTrackEntriesManager entries;
49  
50  	/***
51  	 * takes the TimeTrackEntriesManager wraper containing the entries so this
52  	 * class can update the duration field.
53  	 * 
54  	 * @param entries TimeTrackEntriesManager 
55  	 */
56  	public StopWatch(TimeTrackEntriesManager entries) {
57  		super();
58  		this.entries = entries;
59  	}
60  
61  	/***
62  	 * runs the timer thread
63  	 */
64  	public void run() {
65  		while (true) {
66  			try {
67  				sleep(UPDATE_INTERVAL);
68  				updateDuration();
69  			} catch (Exception e) {
70  				TimeTrackLog.logInfo("caught an Exception while running stopWatch, "+e.getLocalizedMessage());
71  				// catching is OK here
72  				// keep on running :-)
73  			}
74  		}
75  	}
76  
77  	/***
78  	 * updates the duration field
79  	 */
80  	public void updateDuration() {
81  		EntryType entryType = entries.getCurrentSelected();
82  		if (entryType != null) {
83  			Calendar startTime = entryType.getStartTime();
84  			Date time = startTime.getTime();
85  			long longTime = time.getTime();
86  			long duration = System.currentTimeMillis() - longTime;
87  			duration = duration / UPDATE_INTERVAL;
88  			entryType.setDuration(duration);
89  			entries.setChanged();
90  			entries.notifyObservers();
91  		}
92  	}
93  }