1

The kotlin function delay() has this specification:

  • Delays coroutine for a given time without blocking a thread and resumes it after a specified time. * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * immediately resumes with [CancellationException].

I want to achieve exact functionality using Java. Basically, I need to run a function using some delay and this should be cancellable anytime by some given condition.

I've already gone through this thread, but most of the answers aren't quite the right fit for my scenario.

Teekam Suthar
  • 529
  • 1
  • 9
  • 20

1 Answers1

2

You are looking for the ScheduledExecutorService.

 // Create the scheduler
    ScheduledExecutorService scheduledExecutorService = 
     Executors.newScheduledThreadPool(1);
    // Create the task to execute
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello");
        }
    };
    ScheduledFuture<?> scheduledFuture =
        scheduledExecutorService. schedule(r, 5, TimeUnit.SECONDS);
  
    // Cancel the task
    scheduledFuture.cancel(false);

when you cancel it an InterruptedException will be thrown.

Maksym Rudenko
  • 706
  • 5
  • 16
  • Thanks Maksym for the snippet, but where do I put this, so that I'll be able to cancel this task from any function within an activity? – Teekam Suthar Sep 17 '20 at 06:08
  • nvm, I put the declaration of scheduledFuture in MainActivity class, and then I'm able to access it anywhere in the activity. but one more thing I need to know if I haven't scheduled anything, and I call this cancel function, is there gonna be any problem? – Teekam Suthar Sep 17 '20 at 06:11
  • I don't 100% understand the question. `schedule` function returns the `scheduledFuture`, so I don't see how you can call it without scheduling... If you have it like so `ScheduledFuture> scheduledFuture;` and then somewhere else `scheduledFuture.cancel(false);` then you most likely getting NullPointerException. P.S. please consider accepting the answer if it satisfies your question. – Maksym Rudenko Sep 17 '20 at 12:20
  • 1
    Yeah, I accepted the answer. Was only waiting for your response! Thank you so much! – Teekam Suthar Sep 18 '20 at 18:06