ScheduledExecutorService执行周期性或定时任务

schedule(Callable<V> callable, long delay, TimeUnit unit)

         创建并执行在给定延迟后启用的 ScheduledFuture。

schedule(Runnable command, long delay, TimeUnit unit)

         创建并执行在给定延迟后启用的一次性操作。

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnitunit)

         创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。

scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,TimeUnit unit)

         创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。

 





schedule方法被用来延迟指定时间来执行某个指定任务。如果你需要周期性重复执行定时任务可以使用scheduleAtFixedRate或者scheduleWithFixedDelay方法,它们不同的是前者以固定频率执行,后者以相对固定频率执行。
 
不管任务执行耗时是否大于间隔时间,scheduleAtFixedRate和scheduleWithFixedDelay都不会导致同一个任务并发地被执行。唯一不同的是scheduleWithFixedDelay是当前一个任务结束的时刻,开始结算间隔时间,如0秒开始执行第一次任务,任务耗时5秒,任务间隔时间3秒,那么第二次任务执行的时间是在第8秒开始。
 
ScheduledExecutorService的实现类,是ScheduledThreadPoolExecutor。ScheduledThreadPoolExecutor对象包含的线程数量是没有可伸缩性的,只会有固定数量的线程。不过你可以通过其构造函数来设定线程的优先级,来降低定时任务线程的系统占用。
 
特别提示:通过ScheduledExecutorService执行的周期任务,如果任务执行过程中抛出了异常,那么过ScheduledExecutorService就会停止执行任务,且也不会再周期地执行该任务了。所以你如果想保住任务都一直被周期执行,那么catch一切可能的异常。

 

package test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* create at 11-10-14
* @author KETQI
* @category
*/
public class TestScheduledThreadPoolExecutor {
    private static SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args{

        //ScheduledExecutorService exec=Executors.newScheduledThreadPool(1);
         ScheduledThreadPoolExecutor  exec  =  new  ScheduledThreadPoolExecutor( 1);
         /**
         *每隔一段时间打印系统时间,互不影响的<br/>
         * 创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;<br/>
         * 也就是将在 initialDelay 后开始执行,然后在initialDelay+period 后执行,<br/>
         * 接着在 initialDelay + 2 * period 后执行,依此类推。
         */
         exec . scheduleAtFixedRate( new  Runnable()  {
             public  void  run()  {
                 System . out . println( format . format( new  Date()));
             }
         },  1000 ,  5000 ,  TimeUnit . MILLISECONDS);

         //开始执行后就触发异常,next周期将不会运行
         exec . scheduleAtFixedRate( new  Runnable()  {
             public  void  run()  {
                 System . out . println( "RuntimeException no catch,next time can't run");
                 throw  new  RuntimeException();
             }
         },  1000 ,  5000 ,  TimeUnit . MILLISECONDS);

         //虽然抛出了运行异常,当被拦截了,next周期继续运行
         exec . scheduleAtFixedRate( new  Runnable()  {
             public  void  run()  {
                 try {
                     throw  new  RuntimeException();
                 } catch ( Exception  e ){
                     System . out . println( "RuntimeException catched,can run next");
                 }
             }
         },  1000 ,  5000 ,  TimeUnit . MILLISECONDS);

         /**
         * 创建并执行一个在给定初始延迟后首次启用的定期操作,<br/>
         * 随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。
         */
         exec . scheduleWithFixedDelay( new  Runnable()  {
             public  void  run()  {
                 System . out . println( "scheduleWithFixedDelay:begin," + format . format( new  Date()));
                 try  {
                     Thread . sleep( 2000);
                 }  catch ( InterruptedException  e{
                     e . printStackTrace();
                 }
                 System . out . println( "scheduleWithFixedDelay:end," + format . format( new  Date()));
             }
         }, 1000 , 5000 , TimeUnit . MILLISECONDS);

         /**
         * 创建并执行在给定延迟后启用的一次性操作。
         */
         exec . schedule( new  Runnable()  {
             public  void  run()  {
                 System . out . println( "The thread can only run once!");
             }
         }, 5000 , TimeUnit . MILLISECONDS);
     }
}






ScheduledExecutorService接口
在ExecutorService的基础上,ScheduledExecutorService提供了按时间安排执行任务的功能,它提供的方法主要有:
  • schedule(task,initDelay):安排所提交的Callable或Runnable任务在initDelay指定的时间后执行。
  • scheduleAtFixedRate():安排所提交的Runnable任务按指定的间隔重复执行
  • scheduleWithFixedDelay():安排所提交的Runnable任务在每次执行完后,等待delay所指定的时间后重复执行。
    代码:ScheduleExecutorService的例子
  • import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.ScheduledFuture;
    import java.util.concurrent.TimeUnit;

    public class ScheduledExecutorServiceTest
    {
           public static void main(String[] args) throws InterruptedException,ExecutionException
           {
                  //*1
                   ScheduledExecutorService service=Executors.newScheduledThreadPool(2);
                   //*2
                   Runnable task1=new Runnable()
                   {
                        public void run()
                        {
                           System.out.println("Taskrepeating.");
                        }
                   };
                   //*3
                   final ScheduledFuture future1=service.scheduleAtFixedRate(task1,0,1,TimeUnit.SECONDS);
                   //*4
                   ScheduledFuture future2=service.schedule(new Callable()
                {
                        public String call()
                        {
                                future1.cancel(true);
                                return "taskcancelled!";
                        }
                   },10,TimeUnit.SECONDS);
                   System.out.println(future2.get());
         //*5
         service.shutdown();
       }
    }

  • 这个例子有两个任务,第一个任务每隔一秒打印一句“Taskrepeating”,第二个任务在5秒钟后取消第一个任务。

    *1:初始化一个ScheduledExecutorService对象,这个对象的线程池大小为2。
    *2:用内函数的方式定义了一个Runnable任务。
    *3:调用所定义的ScheduledExecutorService对象来执行任务,任务每秒执行一次。能重复执行的任务一定是 Runnable类型。注意我们可以用TimeUnit来制定时间单位,这也是Java5.0里新的特征,5.0以前的记时单位是微秒,现在可精确到奈秒。
    *4:调用ScheduledExecutorService对象来执行第二个任务,第二个任务所作的就是在5秒钟后取消第一个任务。

    *5:关闭服务







  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值