JavaTimer

编程

2. Schedule a Task Once

Let"s start by simply running a single task with the help of a Timer:

1

2

3

4

5

6

7

8

9

10

11

12

13

@Test

public

void

givenUsingTimer_whenSchedulingTaskOnce_thenCorrect() {

    

TimerTask task =

new

TimerTask() {

        

public

void

run() {

            

System.out.println(

"Task performed on: "

+

new

Date() +

"n"

+

              

"Thread"s name: "

+ Thread.currentThread().getName());

        

}

    

};

    

Timer timer =

new

Timer(

"Timer"

);

     

    

long

delay = 1000L;

    

timer.schedule(task, delay);

}

Note that if we are running this is a JUnit test, we should add a Thread.sleep(delay * 2) call to allow the Timer"s thread to run the task before the Junit test stops executing.

3. Schedule a Repeated Task at an Interval

Next – let"s schedule a task to run at a pre-defined interval.

We"ll make use of the scheduleAtFixedRate(repeatedTask, delay, period) API – which schedules the task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at regular intervals, separated by the specified period:

1

2

3

4

5

6

7

8

9

10

11

12

13

@Test

public

void

givenUsingTimer_whenSchedulingRepeatedTask_thenCorrect(){

    

TimerTask repeatedTask =

new

TimerTask() {

        

public

void

run() {

            

System.out.println(

"Task performed on "

+

new

Date());

        

}

    

};

    

Timer timer =

new

Timer(

"Timer"

);

     

    

long

delay  = 1000L;

    

long

period = 1000L;

    

timer.scheduleAtFixedRate(repeatedTask, delay, period);

}

Note that – if an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to “catch up”.

3.1. Schedule a Daily Task

Next – let"s run a task once a day:

1

2

3

4

5

6

7

8

9

10

11

12

13

@Test

public

void

givenUsingTimer_whenSchedulingDailyTask_thenCorrect() {

    

TimerTask repeatedTask =

new

TimerTask() {

        

public

void

run() {

            

System.out.println(

"Task performed on "

+

new

Date());

        

}

    

};

    

Timer timer =

new

Timer(

"Timer"

);

     

    

long

delay = 1000L;

    

long

period = 1000L * 60L * 60L * 24L;

    

timer.scheduleAtFixedRate(repeatedTask, delay, period);

}

4. Cancel Timer and TimerTask

An execution of a task can be canceled in a few ways:

4.1. Cancel the TimerTask Inside Run

By calling the TimerTask.cancel() method inside the run() method"s implementation of the TimerTask itself:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@Test

public

void

givenUsingTimer_whenCancelingTimerTask_thenCorrect()

  

throws

InterruptedException {

    

TimerTask task =

new

TimerTask() {

        

public

void

run() {

            

System.out.println(

"Task performed on "

+

new

Date());

            

cancel();

        

}

    

};

    

Timer timer =

new

Timer(

"Timer"

);

     

    

timer.scheduleAtFixedRate(task, 1000L, 1000L);

     

    

Thread.sleep(1000L *

2

);

}

4.2. Cancel the Timer

By calling the Timer.cancel() method on a Timer object:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@Test

public

void

givenUsingTimer_whenCancelingTimer_thenCorrect()

  

throws

InterruptedException {

    

TimerTask task =

new

TimerTask() {

        

public

void

run() {

            

System.out.println(

"Task performed on "

+

new

Date());

        

}

    

};

    

Timer timer =

new

Timer(

"Timer"

);

     

    

timer.scheduleAtFixedRate(task, 1000L, 1000L);

     

    

Thread.sleep(1000L *

2

);

    

timer.cancel();

}

4.3. Stop the Thread of the TimerTask Inside Run

You can also stop the thread inside the run method of the task, thus canceling the entire task:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@Test

public

void

givenUsingTimer_whenStoppingThread_thenTimerTaskIsCancelled()

  

throws

InterruptedException {

    

TimerTask task =

new

TimerTask() {

        

public

void

run() {

            

System.out.println(

"Task performed on "

+

new

Date());

            

// TODO: stop the thread here

        

}

    

};

    

Timer timer =

new

Timer(

"Timer"

);

     

    

timer.scheduleAtFixedRate(task, 1000L, 1000L);

     

    

Thread.sleep(1000L *

2

);

}

Notice the TODO instruction in the run implementation – in order to run this simple example, we"ll need to actually stop the thread.

In a real-world custom thread implementation, stopping the thread should be supported, but in this case we can ignore the deprecation and use the simple stop API on the Thread class itself.

5. Timer VS ExecutorService

You can also make good use of an ExecutorService to schedule timer tasks, instead of using the timer.

Here"s a quick example of how to run a repeated task at a specified interval:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@Test

public

void

givenUsingExecutorService_whenSchedulingRepeatedTask_thenCorrect()

  

throws

InterruptedException {

    

TimerTask repeatedTask =

new

TimerTask() {

        

public

void

run() {

            

System.out.println(

"Task performed on "

+

new

Date());

        

}

    

};

    

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    

long

delay  = 1000L;

    

long

period = 1000L;

    

executor.scheduleAtFixedRate(repeatedTask, delay, period, TimeUnit.MILLISECONDS);

    

Thread.sleep(delay + period *

3

);

    

executor.shutdown();

}

So what are the main differences between the Timer and the ExecutorService solution:

  • Timer can be sensitive to changes in the system clock; ScheduledThreadPoolExecutor is not
  • Timer has only one execution thread; ScheduledThreadPoolExecutor can be configured with any number of threads
  • Runtime Exceptions thrown inside the TimerTask kill the thread, so following scheduled tasks won"t run further; with ScheduledThreadExecutor – the current task will be canceled, but the rest will continue to run

6. Conclusion

This tutorial illustrated the many ways you can make use of the simple yet flexible Timer and TimerTask infrastructure built into Java, for quickly scheduling tasks. There are of course much more complex and complete solutions in the Java world if you need them – such as the Quartz library – but this is a very good place to start.

The implementation of these examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.

以上是 JavaTimer 的全部内容, 来源链接: utcz.com/z/513069.html

回到顶部