gsharew
gsharew

Reputation: 283

Call ExectuorService with time interval - android

i used a custom thread to fetch data in the background every 1 second by making a thread goes to sleep, but my App crashes and throws exception OutOfMemoryError. Now i read a documentation in android developer and i understand that using custom thread is bad practice as it is difficult to manage the memory consistency. but finally i found ExecutorService very interesting when we need to do some tasks on background So, i decided to use it.

As You know the ExecutorService is like below:

public void executeTask()
{
    ExecutorService executroService = new Executor.newSingleThreadExecutor();
    executroService.execute(new Runnable()
    {
       @Override
       publi void run()
       {
          // now execute the server request
       }  
    });

}

Now how can i achive calling to executorService every 1 second untill the user goes to onpause() state or untill the user shifts from the current activity to another activity? if i use a custom thread to call that service, the App goes to crash. so how can i achive that ?

Upvotes: 0

Views: 36

Answers (1)

Narendra_Nath
Narendra_Nath

Reputation: 5173

What you need is a ScheduledExecutorService

It can schedule commands to run after a given delay, or to execute periodically.

Here is a code that implements this

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
   private final ScheduledExecutorService scheduler =
     Executors.newScheduledThreadPool(1);

   public void beepForAnHour() {
     Runnable beeper = () -> System.out.println("beep");
     ScheduledFuture<?> beeperHandle =
       scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
     Runnable canceller = () -> beeperHandle.cancel(false);
     scheduler.schedule(canceller, 1, HOURS);
   }
 }

Upvotes: 1

Related Questions