Java定时器Timer

Java定时器Timer的使用

创建Timer对象: Timer timer = new Timer();

创建TimerTask执行任务:

      //定义成员变量;
      int number = 8;
      boolean isCancelTimer = false;

      TimerTask timerTask = new TimerTask()
        {
            int count = 0;
            @Override
            public void run()
            {
                PhoneBookDataSource phoneBookDataSource =
                        (PhoneBookDataSource) PhoneBookDataSource.getInstance(mContext);
                //获取callLogList,if CallLogList.size 大于0,则取消定时任务;
                List callLogList = phoneBookDataSource.getCallLogList();
                if (callLogList.size() > 0)
                {
                    isCancelTimer = true;
                }
                if (isCancelTimer || count == number)
                {
                    timer.cancel();
                    isCancelTimer = false;
                }
                else if (count < number)
                {
                    mHandler.sendEmptyMessage(REQUEST_CONTACTS);
                }
                count++;
            }
        };

**Timer执行任务 --> ** 任务:timerTask,0:间隔0秒开始执行,每次执行间隔4000毫秒;

        timer.schedule(timerTask, 0, 4000);

你可能感兴趣的:(Java基础,java)