Execute AsyncTask every three seconds - java

I built one AsyncTask class that returns a specific value. This value changes frequently, so, I need to call my AsyncTask class multiple times to show the value updated.
I'm getting on a different class the result from the AsyncTask.
try {
output = new task().execute(getconversationid).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And when the result from the AsyncTask updates, I call my other Class again to update everything.
private void call() {
new GetContacts().execute(id);
}
...
mobilemessages = contacts.length();
...
myNum = Integer.parseInt(output);
if(myNum != mobilemessages) {
call();
}
My question is how can i set a Timer or a Handler to update my class call(task) every three seconds?
Thank you.

Use Thread.sleep(3000); 3000 is in milliseconds.
Try{
Thread.sleep(3000);
}catch(Exception ex){
}

Related

Java: gRPC with FutureStub and ListenableFuture

I'm learning gRPC with Java and as an example I've defined three request types (cuboid, sphere and cylinder) and a single response type (String) where I put message about the calculated volume of a specific geometry. I followed this example, which use blocking stub on the client side and the program runs correctly. However, I want to try the asynchronous approach, so here is my client side code, written with newFutureStub and ListenableFuture:
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost",8080)
.usePlaintext()
.build();
GeometryServiceGrpc.GeometryServiceFutureStub stub = GeometryServiceGrpc.newFutureStub(channel);
ListenableFuture<Response> cuboidResp = stub.calcCuboidVol(CuboidVolumeRequest.newBuilder()
.setLength(2)
.setWidth(3)
.setHeight(4)
.build());
cuboidResp.addListener(() -> {
try {
System.out.println(cuboidResp.get().getResponse());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}, command -> {
command.run();
});
ListenableFuture<Response> sphereResp = stub.calcSphereVol(SphereVolumeRequest.newBuilder()
.setRadius(2)
.build());
sphereResp.addListener(() -> {
try {
System.out.println(sphereResp.get().getResponse());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}, command -> {
command.run();
});
ListenableFuture<Response> cylinderResp = stub.calcCylinderVol(CylinderVolumeRequest.newBuilder()
.setRadius(2)
.setHeight(3)
.build());
cylinderResp.addListener(() -> {
try {
System.out.println(cylinderResp.get().getResponse());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}, command -> {
command.run();
});
channel.shutdown();
}
Since we must use ListenableFuture I attach its method addListener() to each return instance of a specific geometry method (the Response message has a single string field called response). Basically, the desired result is just to print the calculations once they're ready and that's why a System.out.println is called in the runnable part. Although the program gets executed successfully, nothing is printed. But if check a specific geometry, then all results appear to the console. Example:
if(!cylinderResp.isDone()) {
try {
cylinderResp.get().getResponse();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
Does this means that the program terminates before the asynchronous part is completed? And is the executable part (commnad) written correctly (I searched and found out that this part can be executed by a ExecutorService if we want the code to be run on different thread(s) - not a requirement in my case)?
Does this means that the program terminates before the asynchronous part is completed? Yes, that's right, you should wait it execute complete by call cylinderResp.get() or channel.awaitTermination(5, TimeUnit.SECONDS);
And is the executable part (commnad) written correctly, If you want run task in specify thread pool you should add a ExecutorService, or it will executed by default thread pool.
For completely asynchronous you should use StreamObserver.
For more detail of how to use gRPC in Java you can reference my code helloworlde/grpc-java-sample

ListenableFuture - how to wait before return

I have a Spring Cloud microservice that posts message on a Kafka broker, this microservice is accessible thru a REST api.
I want to return the submit status back to the caller but seems like Java does not await. How to make this to wait either success or failure before my code returns?
Heres the code:
kafkaProduc.send("topictest", msg).addCallback(
new ListenableFutureCallback<SendResult<String, ExecutionDataMessage>>() {
#Override
public void onSuccess(SendResult<String, ExecutionDataMessage> result) {
eresp.status = "ok";
eresp.msg = "message submitted successfully";
}
#Override
public void onFailure(Throwable ex) {
eresp.status = "error";
eresp.msg = "failure while sending data to kafka. exception: " + ex.getMessage();
}
});
HttpStatus erespStatus = eresp.status == "ok" ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST;
return new ResponseEntity<ExecutionResponse>(eresp, erespStatus);
The callback is for when you want an asynchronous result. If you want to block the calling thread, use future.get()...
ListenableFuture<SendResult<String, String>> future = template.send("foo", "bar");
try {
SendResult<String, String> sendResult = future.get(10, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Thread.currentThread.interrupt();
}
catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kafkaproducer.send returns a future. If you want to wait then perhaps you would prefer the following:
kafkaProduc.send("topictest", msg).get(1L, TimeUnit.SECONDS);
Then failures are likely to raise an exception rather than invoking your on error callback.

Using multithreading get response from different urls

I am making an ajax call to a Java servlet which gets response from different urls and manipulate the data before sending back. Now as there are many urls, to speed up the process rather than sequential processing I have used CountDownLatch and made a class for each url response(which I will use for multithreading). I am not able to understand how to send data back from each response class to the main servlet so that I can manipulate and send back the data to ajax call.
Here's the doget() of my servlet which is called through ajax call.
private static CountDownLatch _latch;
private static int N = 2;
_latch = new CountDownLatch(N);
try {
new Thread(new FirstUrl(_latch)).start();
new Thread(new SecondUrl(_latch)).start();
_latch.await();
}
catch (InterruptedException e) {
e.printStackTrace();
}
Here are the url response classes.
public class SecondUrl implements Runnable {
private CountDownLatch _latch = null;
public SecondUrl(CountDownLatch _latch) {
this._latch = _latch;
}
public void run() {
URI uri;
try {
uri = new URI("http://url1.com");
JSONTokener tokener = new JSONTokener(uri.toURL().openStream());
JSONObject root = new JSONObject(tokener);
_latch.countDown();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Similarly, there is another class with a different url. How to send the JSONObject result back to servlet, so that I can manipulate it.
I am new to multithreading so I might be wrong about any approach. Feel free to point out. Thanks.
Make use of the Callable instead of Runnable. Look at Future interface.
One (of the many) way (to pass result back from your threads) is to pass to your threads a reference to a ArrayBlockingQueue that is initialized in your main thread. The result can be added to the queue. In the main thread, you can either process as the data becomes available or process at the end (after you finish you _latch.await()).
try using a synchronized method to 'join' result in each individual thread, Using Runnable is fine.
And you don't need a second class for SecondUrl. you can use a single class and you can pass the url as a parameter to the class.

IF and ELSE in TRY CATCH?

I have this code
root = new Root();
root.checkRootMethod2();
TextView=(TextView)view.findViewById(R.id.textView4);
if(root.checkRootMethod2()) {
TextView.setText(Html.fromHtml("<b>TEXT 01</b><br>"));
} else {
TextView.setText(Html.fromHtml("<b>TEXT 02</b><br>"));
}
try {
if (root.RootAvailibility() && (root.checkRootMethod3())) {
try {
Process process = Runtime.getRuntime().exec("su");
OutputStream stdin = process.getOutputStream();
stdin.flush();
stdin.close();
} catch(Exception e) {
}
TextView.append(Html.fromHtml(
"<b><font color=\"green\">TEXT 03</b></font>"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
root.busybox();
TextView.append(Html.fromHtml(
"<br><b><font color=\"green\">TEXT 04</b></font>"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {
TextView.append(Html.fromHtml(
"<br><b><font color=\"red\">TEXT05</b></font>"));
}
I wish that if if (root.RootAvailibility() && (root.checkRootMethod3())) return true Viewing a TextView that says something.If return false, another TextView that displays something else. As happens for root.checkRootMethod2 (); Same goes for root.busybox (); Do you have any idea on how I can do? Now visualize always Text04
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
/// your code ...
}
catch(Exception e){ }
TextView.append(Html.fromHtml("<b><font color=\"green\">TEXT 03</b></font>"));
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Codes here runs always regardless of if clause.
the code (try block in your case) runs regardless of the if condition as the try block clears the scope of if block.
Either put try completely inside if block or surround both if,else statement by a single try block.
I don't know what is the need of multiple try/catch here :
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
You can add one more catch(Exception e) to the upper try/catch block and that will serve the same purpose.
Secondly there is no else part to this if (root.RootAvailibility() && (root.checkRootMethod3())). So, if it is false the program will simply move forward.
Well you're always going to see Text04 because there's no conditional that excludes it. The try catch block it's in is at the top level.
It would help if you could provide a short, self-contained, compilable example of your code. There's clearly other potentially relevant code missing. For example, the try that goes with that last catch block. Also, it might help you to comment the beginning and end of your code blocks so that you can tell what's included in the if else statements.

how can i call a throwable method inside a runnable, for creating a new thread

while trying to create a progressbar in android i came across this problem.
i am following this example : http://developer.android.com/reference/android/widget/ProgressBar.html
my problem is that one of my methods i want to call has to be inside a try and catch
how do i do that inside of a runnable?
Runnable SendThread = new Runnable()
{
try
{
GetAndConvertImagesToPdf();
mProgStatus = 30;
mProgress.setProgress(mProgStatus);
title.setText(R.string.sendingTitle);
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
};
i get this error:
"Syntax error on token try, delete this token"
how can i resolve this?
thank you
u put the try in the class body its not in any method or block
this is more like it
Runnable SendThread = new Runnable() {
public void run() {
try {
GetAndConvertImagesToPdf();
mProgStatus = 30;
mProgress.setProgress(mProgStatus);
title.setText(R.string.sendingTitle);
}
catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Sorry I am not able to answer your question but I have one advice,Try to explore about AsyncTask it will help you to run a background thread and it will let you update your UI thread as well at same time. however good luck for your current question.
link : http://developer.android.com/reference/android/os/AsyncTask.html
Happy Coding!

Categories