Java定时器Timer

Java

创建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<PhoneBook> 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++;
            }
        };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

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

        timer.schedule(timerTask, 0, 4000);

最新项目