Home > database >  Is there a way to schedule a task until an event occurs or a specific amount of time passes?
Is there a way to schedule a task until an event occurs or a specific amount of time passes?

Time:08-25

Let's say I have a task that will check if a certain condition has been met. If that condition has been met, I should terminate the task early. However, I should continue to run the task for N number of minutes while continuously checking if that condition has been met. At the end of N minutes, the task should terminate itself.

I've been looking into Timer, TimerTask, and ExecutorService, but none of them seem to offer the type of solution I am looking for. For example, these approaches will allow you to schedule a task to run once, or repeatedly, but not for a specific amount of time (aka N minutes).

CodePudding user response:

ScheduledExecutorService can accomplish this.

What you need to do:

  • Schedule the block of work you want to do at a fixed interval (in time units, so like seconds, minutes, hours, etc)
  • When you've completed the work, execute ScheduledExecutorService#shutdownNow
  • To time out after a period of time, use ScheduledExecutorService#awaitTermination to delay the termination of the scheduled task until your threshold elapses
  •  Tags:  
  • java
  • Related