当前位置: 移动技术网 > IT编程>开发语言>Java > Java定时任务的三种实现方法

Java定时任务的三种实现方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

译者注:个人觉得用定时任务来跑垃圾回收不是很好的例子,从译者接触到的项目来看,比较常见的是用定时任务来进行非实时计算,清除临时数据、文件等。
在本文里,我会给大家介绍3种不同的实现方法:
1.普通thread实现
2.timertask实现
3.scheduledexecutorservice实现

一、普通thread

这是最常见的,创建一个thread,然后让它在while循环里一直运行着,通过sleep方法来达到定时任务的效果。这样可以快速简单的实现,代码如下:

复制代码 代码如下:

public class task1 {
public static void main(string[] args) {
  // run in a second
  final long timeinterval = 1000;
  runnable runnable = new runnable() {
  public void run() {
    while (true) {
      // ------- code for task to run
      system.out.println("hello !!");
      // ------- ends here
      try {
       thread.sleep(timeinterval);
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
      }
    }
  };
  thread thread = new thread(runnable);
  thread.start();
  }
}

二、用timer和timertask

上面的实现是非常快速简便的,但它也缺少一些功能。
用timer和timertask的话与上述方法相比有如下好处:

1.当启动和去取消任务时可以控制
2.第一次执行任务时可以指定你想要的delay时间

在实现时,timer类可以调度任务,timertask则是通过在run()方法里实现具体任务。
timer实例可以调度多任务,它是线程安全的。
当timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。
下面是代码:

复制代码 代码如下:

import java.util.timer;
import java.util.timertask;
public class task2 {
  public static void main(string[] args) {
    timertask task = new timertask() {
      @override
      public void run() {
        // task to run goes here
        system.out.println("hello !!!");
      }
    };
    timer timer = new timer();
    long delay = 0;
    long intevalperiod = 1 * 1000;
    // schedules the task to be run in an interval
    timer.scheduleatfixedrate(task, delay,
                                intevalperiod);
  } // end of main
}

这些类从jdk 1.3开始存在。

三、scheduledexecutorservice

scheduledexecutorservice是从java se 5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。
相比于上两个方法,它有以下好处:

1.相比于timer的单线程,它是通过线程池的方式来执行任务的
2.可以很灵活的去设定第一次执行任务delay时间
3.提供了良好的约定,以便设定执行的时间间隔

下面是实现代码,我们通过scheduledexecutorservice#scheduleatfixedrate展示这个例子,通过代码里参数的控制,首次执行加了delay时间。

复制代码 代码如下:

import java.util.concurrent.executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.timeunit;
public class task3 {
  public static void main(string[] args) {
    runnable runnable = new runnable() {
      public void run() {
        // task to run goes here
        system.out.println("hello !!");
      }
    };
    scheduledexecutorservice service = executors
                    .newsinglethreadscheduledexecutor();
    service.scheduleatfixedrate(runnable, 0, 1, timeunit.seconds);
  }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网