Home  >  Article  >  Web Front-end  >  Detailed explanation of the usage of Timer in Java_jquery

Detailed explanation of the usage of Timer in Java_jquery

WBOY
WBOYOriginal
2016-05-16 15:36:001740browse

Now the project uses a function that needs to check whether files are updated regularly. timer is used exactly here.

The usage is very simple, just create a new timer and then write a subclass of timertask.

The code is as follows:

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, mytask can be executed after 1 second and executed every two seconds.

Of course, the function of timer can also be achieved by constructing a thread yourself, and then using sleep in the thread to simulate stopping for a period of time and then performing an action.

In fact, if you look at the source code of timertask, you can immediately know that timertask implements the runnable interface. In other words, using a timer to perform an operation at intervals is also done through a thread.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn