Teekam Suthar
Teekam Suthar

Reputation: 459

How to run a cancellable scheduled task in java

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.

Upvotes: 1

Views: 1122

Answers (1)

Maksym Rudenko
Maksym Rudenko

Reputation: 746

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.

Upvotes: 2

Related Questions