Search code examples
javadelaytiming

Unlock objects on specified date/time


I want to implement a function with which I will be able to lock a user account and store a date on which the user account will be unlocked.

Is something like this possible, or only way is do it with Timer().schedule(new TimerTask()?


Solution

  • You can use a DelayQueue for your purpose.

    https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/DelayQueue.html

    You can put entries into the delayed queue with specifying unlocking time.

    Create a blocking delayed queue

    BlockingQueue queue = new DelayQueue();
    

    Then put your object implementing Delayed interface into the queue. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Delayed.html

    public class DelayObject implements Delayed {
    

    Then you can wait for your objects to expire by using the blocking queue's take() method

    See this tutorial https://www.baeldung.com/java-delay-queue