Home  >  Article  >  Web Front-end  >  Java中Timer的用法详解_jquery

Java中Timer的用法详解_jquery

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

现在项目中用到需要定时去检查文件是否更新的功能。timer正好用于此处。

用法很简单,new一个timer,然后写一个timertask的子类即可。

代码如下:

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"); 
  } 
} 

这样,就可以在1秒钟之后开始执行mytask,每两秒钟执行一次。

当然,timer的功能也可以通过自己构造线程,然后在线程中用sleep来模拟停止一段时间,然后再执行某个动作。

其实,看一下timertask的源码就立即可以知道,timertask就是实现了runnable接口的。也就是说,通过timer来间隔一段时间执行一个操作,也是通过一个线程来做到的。

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