Home > Enterprise >  How to run a function every "N" seconds with different parameter each time?
How to run a function every "N" seconds with different parameter each time?

Time:03-04

I have a function that makes API call to the server and updates the UI with new data. I want to make, so that every 30 seconds I make API call with different url each time ? And these API calls should be non-stop, as long as the app is running.

String url1 = "https://somewebsite.com/api/update-rates?locale=en";
String url2 = "https://somewebsite.com/api/update-rates?locale=ru";
String url3 = "https://somewebsite.com/api/update-rates?locale=fr";

public void getFreshRates (String url) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if(response.isSuccessful()) {
                    String myResponse = response.body().string();
                     // Handling the response here
                     }

                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // Updating My UI here
                        }
                    });
                }
        });
    }

CodePudding user response:

To run every 30 seconds you can use the solution of this post: Running a Java Thread in intervals

And also, maybe you can use CompletableFuture to do asynchronous calls and retrieve the result:

CompletableFuture<Void> future1  
  = CompletableFuture.supplyAsync(() -> getFreshRates(url1));
CompletableFuture<Void> future2  
  = CompletableFuture.supplyAsync(() -> getFreshRates(url2));
CompletableFuture<Void> future3  
  = CompletableFuture.supplyAsync(() -> getFreshRates(url3));

CompletableFuture<Void> combinedFuture 
  = CompletableFuture.allOf(future1, future2, future3);
    
combinedFuture.get();

See: https://www.baeldung.com/java-completablefuture#Multiple

CodePudding user response:

Is it a fixed number of URLs? Because if it is, you can create N completable futures and run them indefinitely.

  • Related