63、使用Timer类来实现定时任务

定时任务

定时任务就是让计算机自动的每隔一段时间执行的代码。
比如要实现这样的一个功能:
让计算机每隔5秒钟,在控制台打印一个www.monkey1024.com
可以使用java.util包下的Timer类和TimerTask类来实现。

TimerTask是一个实现了Runnable接口的抽象类,需要编写一个类继承TimerTask类,将要在定时任务执行的代码编写在run方法中。

package com.sutaoyu.volatlt;

import java.util.TimerTask;

public class MyRimerTask extends TimerTask{
    
    public void run() {
        System.out.println("www.monkey1024.com");
    }
}

要想执行定时任务,需要创建Timer的对象并调用里面的schedule方法,在Timer类中有多个重载的schedule方法,这里咱们使用这个:

schedule(TimerTask task, Date firstTime, long period);

第一个参数接收TimerTask对象,即上面创建的MyTimerTask
第二参数的Date类型是定时任务执行的开始时间
第三个参数指定定时任务每隔多少毫秒执行一次

package com.sutaoyu.volatlt;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Timer;

public class VolatileTest01 {
    public static void main(String[] args) throws IOException, ParseException{
        Timer t = new Timer();
        t.schedule(new MyTimerTask(), new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").parse("2017-07-03 18:09:00 000"), 5000);
    }
}

猜你喜欢

转载自www.cnblogs.com/zhuifeng-mayi/p/10161146.html