The usage is simple, new a timer, and then write a timertask subclass.
The code is as follows:
[Java] View plaincopy
- package comz.autoupdatefile;
-   
- import java.util.timer;
- import java.util.timertask;
-   
- public   class  M {  
- public   static   void main (String[] args) {
- todo todo.generated by zoer   
- timer timer = new timer ();
- timer.schedule (new mytask (), 1000 ,  2000
- }
- }
-   
- class  MYTASK  extends timertask {
-   
- @Override   
- public   void run () {
- system.out.println (" dddd "
- }
- }
In this way, you can start executing mytask after 1 seconds, once every two seconds.
Of course, the function of a timer can also be constructed by itself, and then by using sleep in the thread to simulate stopping for a period of time before performing an action.
In fact, look at the source of TimerTask can immediately know, TimerTask is implements the Runnable interface the. In other words, a timer to perform an operation over a period of time is also done by a thread.
The run () method is implemented in the interface
Usage of timer in Java