定时器

2019-01-17  本文已影响0人  luckee

定时器 :Timer和TimerTask

定时器例子
定时器原理
做项目很多时候会用到定时任务,比如在深夜,流量较小的时候,做一些统计工作。早上定时发送邮件,更新数据库等。这里可以用Java的Timer或线程池实现。Timer可以实现,不过Timer存在一些问题。他起一个单线程,如果有异常产生,线程将退出,整个定时任务就失败(一个定时器可以有多个任务在里面)。Timer类的作用是设置计划任务,而封装任务内容的类是TimerTask,此类是一个抽象类,继承需要实现一个run方法,通过查文档我们看到Timer有以下几个构造函数:

Timer构造函数
Timer方法.png
从源码可以看到Timer持有一个线程对象,当新建一个Timer对象后,线程就开启了
public class Timer {
    /**
     * The timer task queue.  This data structure is shared with the timer
     * thread.  The timer produces tasks, via its various schedule calls,
     * and the timer thread consumes, executing timer tasks as appropriate,
     * and removing them from the queue when they're obsolete.
     */
    private final TaskQueue queue = new TaskQueue();

    /**
     * The timer thread.
     */
    private final TimerThread thread = new TimerThread(queue);

/**
     * Creates a new timer.  The associated thread does <i>not</i>
     * {@linkplain Thread#setDaemon run as a daemon}.
     */
    public Timer() {
        this("Timer-" + serialNumber());
    }

/**
     * Creates a new timer whose associated thread has the specified name.
     * The associated thread does <i>not</i>
     * {@linkplain Thread#setDaemon run as a daemon}.
     *
     * @param name the name of the associated thread
     * @throws NullPointerException if {@code name} is null
     * @since 1.5
     */
    public Timer(String name) {
        thread.setName(name);
        thread.start();
    }

从TimerTask的源码可以看出,实际上是个Runnable,所以定时器的原理就是Timer作为线程,TimerTask作为任务

/**
 * A task that can be scheduled for one-time or repeated execution by a Timer.
 *
 * @author  Josh Bloch
 * @see     Timer
 * @since   1.3
 */

public abstract class TimerTask implements Runnable {

一个例子,删除文件

package com.wang.reflect;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


class MyTask extends TimerTask{
/**
 * 定时删除指定位置的文件,(这里以删除f盘下aa文件夹的所有文件为例)
 */
    @Override
    public void run() {
        File file=new File("f://aa");
        deleteFolder(file);
        
    }
    public void deleteFolder(File file){
        File[] files=file.listFiles();
        for(File f:files){
            if(f.isDirectory()){
                //使用递归
                deleteFolder(f);
            }else{
                f.delete();
            }
        }
        file.delete();//别忘了把自己删了
    }
    
}
public class TimerDemo {

    public static void main(String[] args) throws ParseException {
        //创建定时器对象
        Timer t=new Timer();
        String time="2019-05-04 11:26:40";
        Date d=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
        t.schedule(new MyTask(), d);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读