您的位置:首页 > 编程语言 > Java开发

java定时任务接口ScheduledExecutorService

2016-10-14 16:12 666 查看
ScheduledExecutorService是从Java SE 5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。

ScheduledExecutorService,是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。

需要注意,只有当调度任务来的时候,ScheduledExecutorService才会真正启动一个线程,其余时间ScheduledExecutorService都是出于轮询任务的状态。

好处:

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

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

public class Test {

 public static void main(String[] args) {

  ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

  int beginTime = TimeUtil.unixTimeStamp();

  Runnable runnable = new Runnable() {

   public void run() {

    // 把run方法里的内容换成你要执行的内容

    int nowTime = TimeUtil.unixTimeStamp();

    System.out.println(nowTime);

    int howlong = nowTime - beginTime;

    //从当前时间开始执行,30秒后停止,关闭定时器

    if (howlong > 30) {

     service.shutdown();

    }

   }

  };

  // public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long

  // initialDelay, long period, TimeUnit unit);

  // command--执行的任务,initialDelay--延迟开始,period--间隔时间,unit--时间单位

  service.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS);

  

 }

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: