Java执行定时任务的方法(Timer、ScheduledExecutorService)

最简单普通的方法:
启动一个线程,在while中调用Thread.sleep即可达到定时的效果,

public class Test {
    public static void main(String[] args) {
        // 1s间隔
        final long timeInterval = 1000;
        Runnable runnable = new Runnable() {
            public void run() {
                while (true) {
                    System.out.println("HelloWorld");
                    try {
                        Thread.sleep(timeInterval);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

2.Timer & TimeTask
Timer是一个定时调度器,可以调度TimerTask
TimerTask是一个抽象类,实现了Runnable接口,但是具体run方法由子类定义

import java.util.Timer;
import java.util.TimerTask;

public class MyTest {

    public static void main(String[] args) {
        Timer timer = new Timer();
        // 匿名类,间隔2s
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                System.out.println("HelloWorld");
            }
        }, 0, 2000);
    }

}

先解释下这个方法:

public void schedule(TimerTask task, long delay, long period)

这个方法是调度一个TimerTask,在delay(ms)后开始调度,每次调度完后,最少等待period(ms)后才开始调度。

来看看Timer的运行:
Timer类包装了一个thread

private final TimerThread thread = new TimerThread(queue);
内部定义:
class TimerThread extends Thread {
……

调度方法:

//调度一个task,经过delay(ms)后开始进行调度,仅调度一次
public void schedule(TimerTask task, long delay)
//指定的时间点time去调度task,仅调度一次
public void schedule(TimerTask task, Date time)
在delay(ms)后开始调度task,每次调度完后,等待period(ms)后再开始调度
public void schedule(TimerTask task, long delay, long period)

public void scheduleAtFixedRate(TimerTask task, long delay, long period)
与上面的区别:
schedule在计算下一次执行的时间的时候,随后的执行时间按照 上一次 **实际执行完成的时间点** 进行计算
scheduleAtFixedRate方法:随后的执行时间按照 上一次开始的 时间点 进行计算

在JDK5.0之后就不建议使用Timer了,缺陷如下:
1.Timer内部是单一线程,如果某个任务执行时间过长,那么将破坏其他TimeTask的定时精确性;
2.Timer线程不会捕获异常的,如果TimerTask抛出的了未检查异常则会导致Timer线程终止,同时不会重新恢复线程的执行,他会错误的认为整个Timer线程都会取消。同时,已经被安排单尚未执行的TimerTask也不会再执行了,新的任务也不能被调度。

解决:
采用ScheduledExecutorService
ScheduledThreadPoolExecutor 是基于相对时间;内部是个线程池,所以可以支持多个任务并发执行。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test {
  public static void main(String[] args) {
    Runnable runnable = new Runnable() {
      public void run() {
        System.out.println("HelloWorld");
      }
    };
    ScheduledExecutorService service = Executors
                    .newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
  }
}

参考:
http://www.aijava.cn/13351.html
Timer与TimerTask的真正原理&使用介绍 http://blog.csdn.net/xieyuooo/article/details/8607220

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值