I need to execute periodic http requests. I use volley for the requests, but I don't want to overflow the queue.
Right now I've got a thread that enqueues the request and waits for 3 seconds.
AtomicBoolean quitUsersWatcher = new AtomicBoolean(false);
class UsersWatcher extends Thread {
final Context context;
ActiveUsersWatcher(Context c) {
context = c;
}
public void run() {
while (!quitUsersWatcher.get()) {
JsonArrayRequest usersRequest = new JsonArrayRequest(Request.Method.GET, Config.ALL_USERS_URL, null,
this::getUsers,
Throwable::printStackTrace
);
try {
RequestQueue queue = MySingleton.getInstance(context).getRequestQueue();
queue.add(usersRequest);
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void getUsers(JSONArray jsonResult) {
//some logic
}
}
But I don't this that sleep
is the best idea.
I thought about a variable that increases by 1 up to 64 or 128 and then enqueues the request.
Like this:
int counter = 0;
while (!quitUsersWatcher.get()) {
if(counter >= 128) {
JsonArrayRequest usersRequest = new JsonArrayRequest(Request.Method.GET,
Config.ALL_USERS_URL, null,
this::getUsers,
Throwable::printStackTrace);
RequestQueue queue = MySingleton.getInstance(context).getRequestQueue();
queue.add(usersRequest);
counter = 0;
}
++counter;
}
But maybe there are some better tools to do something like this. I tried to search for a watcher, but I couldn't find anything useful.
How would you implement something like this?