Home > database >  Execute a block of code after certain time in Java
Execute a block of code after certain time in Java

Time:10-07

I would like to execute a block of code in a thread after a mount of time.

In the thread:

public void run() {
    System.out.println("it is running");
    while (true) {
        if (System.currentTimeMillis() > lastEdit) {
            System.out.println("DELETE");
            timerStart(12000);
        }
    }
}

public static void timerStart(int time) {
    lastEdit = System.currentTimeMillis()   time;
}

In this block of code, the System.out.println("DELETE") will execute after 12s. However, I would also call timeStart function in another code, which is the following

anotherThread.timerStart(12000);

When I call this function, I expect the lastEdit will increase 12000 milli sec. However, it doesn't work. May I know why and how to solve this problem? Thanks.

CodePudding user response:

Hi so you could be using ScheduledExecutorService, take a look to oracle docs, you will find an example, I believe solves your problem

CodePudding user response:

Not sure I understand what you're really trying to do, but changing your run() function so that it spends most of its time "sleeping" might improve the performance of your program:

public void run() {
    System.out.println("it is running");
    while(true) {
        long timeUntilDelete = lastEdit - System.currentTimeMillis();
        if (timeUntilDelete > 0) {
            try {
                Thread.sleep(timeUntilDelete);
            }
            catch(InterruptedException ex) {
                ...What you do here is up to you...
            }
            continue;
        }
        System.out.println("DELETE");
        timerStart(12000);
    }
}
  • Related