简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM