Cecil
Cecil

Reputation: 21

Execute a block of code after certain time in Java

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.

Upvotes: 0

Views: 168

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27115

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);
    }
}

Upvotes: 1

vcg
vcg

Reputation: 176

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

Upvotes: 0

Related Questions