1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.mail.utils;
18 
19 import android.os.Handler;
20 import android.os.Looper;
21 import android.os.Message;
22 import android.os.SystemClock;
23 
24 /**
25  * Class to queue tasks.  This delay the specified task by the specified time, up to the maximum
26  * duration from the time that the first request was received
27  */
28 public abstract class DelayedTaskHandler extends Handler {
29     private final int mDelayMs;
30 
31     private static final long UNSET_TIME = -1;
32 
33     /**
34      * Tracks the time when a task was queued, when there had been no pending task.
35      */
36     private long mLastTaskExecuteTime = UNSET_TIME;
37 
DelayedTaskHandler(Looper looper, int defaultDelayMs)38     public DelayedTaskHandler(Looper looper, int defaultDelayMs) {
39         super(looper);
40         mDelayMs = defaultDelayMs;
41     }
42 
43     /**
44      * Schedule the task to be run after the default delay.
45      */
scheduleTask()46     public void scheduleTask() {
47         final long currentTime = SystemClock.elapsedRealtime();
48         removeMessages(0);
49         if (mLastTaskExecuteTime == UNSET_TIME ||
50                 ((mLastTaskExecuteTime + mDelayMs) <  currentTime)) {
51             // If this is the first task that has been queued or if the last task ran more than
52             // long enough ago that we don't want to delay this task, run it now
53             sendEmptyMessage(0);
54         } else {
55             // Otherwise delay this task for the specify delay duration
56             sendEmptyMessageDelayed(0, mDelayMs);
57         }
58     }
59 
60     @Override
dispatchMessage(Message msg)61     public void dispatchMessage(Message msg) {
62         onTaskExecution();
63         performTask();
64     }
65 
66     /**
67      * Called when the task managed by this handler is executed.  This method can also be called
68      * to indicate that the task has been started externally.
69      *
70      * This updates the handler's internal timestamp.
71      */
onTaskExecution()72     public void onTaskExecution() {
73         mLastTaskExecuteTime = SystemClock.elapsedRealtime();
74     }
75 
76     /**
77      * Method to perform the needed task.
78      */
performTask()79     protected abstract void performTask();
80 }
81