Java-jdk自带的Timer定时器的使用示例

jdk自带的Timer定时器的使用示例

Timer定时器

package com.wodedata.task;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TaskManager {
    //对象
    SomeService someService = new SomeService();
    //日期
    Date date = new Date();
    //每次提前3秒钟执行任务
    long three_second = 3000;
    //定时器
    Timer timer = new Timer();
    //执行任务
    public void runTask(){
        System.out.println("start schedule task .......");
        timer.schedule(new TargetTask(),0);
    }
    /**
     * 任务
     * @author luowei
     */
    private class TargetTask extends TimerTask {
        @Override
        public void run() {
            Long expir_in = Long.valueOf(someService.doSomeThing());
            date.setTime(expir_in-three_second);
            timer.schedule(new TargetTask(), date);
            System.out.println("task has run.......");
        }
    }
    /**
     * main方法
     * @param args 参数
     */
    public static void main(String[] args) {
        TaskManager manager = new TaskManager();
        manager.runTask();
    }
}
/**
 * 目标service,需要定时执行目标service中的doSomeThing方法
 * @author luowei
 *
 */
class SomeService{
    /**
     * 返回long型格式的时间字符串
     * @return 字符串
     */
    public String doSomeThing() {
        Date date = new Date();
        date.setTime(date.getTime()+5000);
        return String.valueOf(date.getTime());
    }
}

版权所有,转载请注明出处 luowei.github.io.