ScheduledThreadPoolExecutor定时使用

来源:互联网 发布:如何去领事馆工作 知乎 编辑:程序博客网 时间:2024/05/16 17:31

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()即可

0 0
原创粉丝点击