g
import java.util.Timer;
import java.util.TimerTask;
class MyTask extends TimerTask {
int counter;
public MyTask() {
counter = 0;
}
public void run() {
counter++;
System.out.println("Ring " + counter);
}
public int getCount() {
return counter;
}
}
public class JTimer {
private boolean running;
private MyTask task;
private Timer timer;
public JTimer() {
timer = new Timer(true);
}
public boolean isRinging() {
return running;
}
public void startRinging() {
running = true;
task = new MyTask();
timer.scheduleAtFixedRate(task, 0, 3000);
}
public void reStart()
{
timer = new Timer();
task = new MyTask();
timer.scheduleAtFixedRate(task, 0, 500);
}
public void doIt() {
running = false;
System.out.println(task.getCount() + " times");
task.cancel();
}
public static void main(String[] args) {
JTimer phone = new JTimer();
phone.startRinging();
try {
System.out.println("started running...");
Thread.sleep(1000);
} catch (InterruptedException e) {
}
phone.doIt();
try {
System.out.println("Thread Stop...");
Thread.sleep(1000);
} catch (InterruptedException e) {
}
phone.reStart();
}
}
음.... 그냥 간단한 소스 이구요 아래소스는 ㅡㅡ..소스어딧더라.....아래 소스는 state 가 아니라 그냥 구현된 소스니,
잘못 보지 않길 바래요...T_T
<pre class="brush:java">
</pre>
public class TimerTest {
Timer timer1;
Timer timer2;
volatile boolean a = false;
public TimerTest() {
timer1 = new Timer();
timer2 = new Timer();
}
public void runStart() {
timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
}
class Task1 extends TimerTask {
public void run() {
System.out.println("Checking a");
a = SomeClass.getSomeStaticValue();
if (a) {
// Pause/stop timer1, start/resume timer2 for 5 seconds
timer2.schedule(new Task2(), 5000);
}
}
}
class Task2 extends TimerTask{
public void run() {
System.out.println("Checking a");
a = SomeClass.getSomeStaticValue();
if (!a) {
// Pause/stop timer2, back to timer1
timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
}
// Do something...
}
}
public static void main(String args[]) {
TimerTest tt = new TimerTest();
tt.runStart();
}
</pre>
ㅎㅎ ㅎ
Reference
[1] I Don't Know ( http://stackoverflow.com/questions/2098642/pausing-stopping-and-starting-resuming-java-timertask-continuously )
-
[1] I Don't Know ( http://stackoverflow.com/questions/2098642/pausing-stopping-and-starting-resuming-java-timertask-continuously )
-
'Language > Java' 카테고리의 다른 글
| [java] java strtok, StringTokenizer (0) | 2012.01.03 |
|---|---|
| [java] Process Runtime 를 이용한 외부(exe)파일 실행 (0) | 2011.11.14 |
| [java] HashMap 사용법, (아니 중첩 arraylist 사용법) (0) | 2011.06.06 |
| [java] List Collection Framework (0) | 2011.06.06 |
| [java] HashMap 의 참조방법(?) (0) | 2011.06.06 |