JAVA中定时器的使用

在JAVA中实现定时器功能要用的二个类是Timer,TimerTask

       Timer类是用来执行任务的类,它接受一个TimerTask做参数
Timer有两种执行任务的模式,最常用的是schedule,它可以以两种方式执行任务:1:在某个时间(Data),2:在某个固定的时间之后(int delay).这两种方式都可以指定任务执行的频率,本文有二个例子,一个是简单的
一个是用了内部类
1.简单实例
  先写一个类
public class TimeTest {
public static void main(String[] args) {
    
     Timer timer = new Timer();
     timer.schedule(new MyTask(),1000,2000);
}

然后再写个类 
public class MyTask  extends TimerTask{

    @Override
    public void run() {
  System.out.println("开始运行");        
    }
}

这样就可以完成一个简单的定时器,但是还有一种方法就是把这二个类写入到一个类中,也就是内部类了

2.内部类

public class SerchRun {

    protected  static void startRun(){
        Timer timer = new Timer();
         TimerTask task =new TimerTask(){
             public void run(){
                 System.out.println("开始运行"); //在这写你要调用的方法
             }
         };
      timer.scheduleAtFixedRate(task, new Date(),2000);//当前时间开始起动 每次间隔2秒再启动
     // timer.scheduleAtFixedRate(task, 1000,2000); // 1秒后启动  每次间隔2秒再启动                 
     }
    
    public static void main(String[] args) {
      SerchRun.startRun();
    }
}

原文地址:https://www.cnblogs.com/renyuan/p/2677303.html