root / tags / v1_0_2_Build_912 / libraries / libGDBMS / src / main / java / com / hardcode / gdbms / engine / internalExceptions / Timer.java @ 11422
History | View | Annotate | Download (1.62 KB)
1 |
package com.hardcode.gdbms.engine.internalExceptions; |
---|---|
2 |
|
3 |
/**
|
4 |
* Reseteable timer. After a cancelTimer or after the execution of the
|
5 |
* scheduled task the object becomes unuseful: It's not possible to schedule
|
6 |
* more tasks
|
7 |
*
|
8 |
* @author Fernando Gonz?lez Cort?s
|
9 |
*/
|
10 |
public class Timer { |
11 |
private boolean cancel = false; |
12 |
private Thread timerThread; |
13 |
|
14 |
/**
|
15 |
* schedules a task
|
16 |
*
|
17 |
* @param task task to schedule
|
18 |
* @param delay delay in milliseconds
|
19 |
*/
|
20 |
public void schedule(Task task, long delay) { |
21 |
timerThread = new Thread(new TimerThread(delay, task)); |
22 |
timerThread.start(); |
23 |
} |
24 |
|
25 |
/**
|
26 |
* restarts the timer
|
27 |
*/
|
28 |
public void resetTimer() { |
29 |
cancel = false;
|
30 |
if (timerThread != null) |
31 |
timerThread.interrupt(); |
32 |
} |
33 |
|
34 |
/**
|
35 |
* cancels the timer. It causes the timer to be unuseful. After this call
|
36 |
* you cannot schedule more tasks
|
37 |
*/
|
38 |
public void cancelTimer() { |
39 |
cancel = true;
|
40 |
timerThread.interrupt(); |
41 |
} |
42 |
|
43 |
/**
|
44 |
* timer thread
|
45 |
*
|
46 |
* @author Fernando Gonz?lez Cort?s
|
47 |
*/
|
48 |
public class TimerThread implements Runnable { |
49 |
long timeout;
|
50 |
Task task; |
51 |
|
52 |
/**
|
53 |
* Creates a new TimerThread.
|
54 |
*
|
55 |
* @param timeout delay in milliseconds
|
56 |
* @param task task to schedule
|
57 |
*/
|
58 |
public TimerThread(long timeout, Task task) { |
59 |
this.timeout = timeout;
|
60 |
this.task = task;
|
61 |
} |
62 |
|
63 |
/**
|
64 |
* @see java.lang.Runnable#run()
|
65 |
*/
|
66 |
public synchronized void run() { |
67 |
while (true) { |
68 |
try {
|
69 |
// Waits the delay
|
70 |
wait(timeout); |
71 |
|
72 |
//executes the task
|
73 |
task.execute(); |
74 |
|
75 |
//exits
|
76 |
break;
|
77 |
} catch (InterruptedException e) { |
78 |
if (cancel) {
|
79 |
break;
|
80 |
} else {
|
81 |
//Volvemos a esperar
|
82 |
} |
83 |
} |
84 |
} |
85 |
} |
86 |
} |
87 |
} |