ScheduledThreadPoolExecutor定时使用

ScheduledThreadPoolExecutor的使用
而不是使用它Timer,其缺点很多,不同可以去百度

(1)定时器的启动,只要调用startTimer()即可

    private void startTimer() {
         if (mTimer != null){
              if (task != null){
              task.cancel();  //将原任务从队列中移除
              System.err.println("task.cancel");
              }
         }
        if (mTimer == null) {
          //构造一个ScheduledThreadPoolExecutor对象,并且设置它的容量为5个

            mTimer = new ScheduledThreadPoolExecutor(5);
             System.err.println("new ScheduledThreadPoolExecutor");
        }


        task = new TimerTask() {

            @Override
            public void run() {
                System.err.println("run");
                startActivityForResult(mainActivity, 100); // 执行

            }


        };
        int delayTime=2;
        //隔2秒后开始执行任务,并且在上一次任务开始后隔一秒再执行一次;
        // mTimer.scheduleWithFixedDelay(task, 2, 1, TimeUnit.SECONDS);
        //隔delayTime秒后执行一次,但只会执行一次。
        mTimer.schedule(task, delayTime, TimeUnit.SECONDS); // delayTime秒后
    }

(2)定时器的停止,只要调用stopTimer()即可

    private void stopTimer() {

        if (mTimer != null) {
            mTimer.shutdown();
            mTimer = null;
        }   
        if (task != null) {  
            task.cancel();  
            task = null;  
        }     

    }

(3)java 具体实现

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

public class TaskTest {
   static ScheduledThreadPoolExecutor stpe = null;
   static int index;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        //构造一个ScheduledThreadPoolExecutor对象,并且设置它的容量为5个
        stpe = new ScheduledThreadPoolExecutor(5);
        MyTask task = new MyTask();
        //隔2秒后开始执行任务,并且在上一次任务开始后隔一秒再执行一次;
        stpe.scheduleWithFixedDelay(task, 2, 1, TimeUnit.SECONDS);
        //隔6秒后执行一次,但只会执行一次。
       // stpe.schedule(task, 6, TimeUnit.SECONDS);
    }

    private static String getTimes() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
        Date date = new Date();
        date.setTime(System.currentTimeMillis());
        return format.format(date);
    }

    private static class MyTask implements Runnable {

        @Override
        public void run() {
            index++;
            System.out.println("2= " + getTimes()+" "  +index);
            if(index >=10){
                stpe.shutdown();
                if(stpe.isShutdown()){
                    System.out.println("停止了????");
                }
            }
        }
    }
}

(4)android 就调用我封装好的函数startTimer()和stopTimer()即可

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值