简体   繁体   中英

java TimerTask increase time?

Hi m using the following timer task,and i want to increase the time of this task when a certain condition occurs

Timer timer2=new Timer();                   
                timer2.schedule(new TimerTask(){
                    public void run(){

                        //whatevr
                    }
                }, 4000);

examlpe

if(mycondition)

{
increase time????
}

how can i do that

Extract the TimerTask in an inner or standalone class. Cancel currently running timer task and schedule a new instance with increased time period.

You can't . You'll have to schedule a new task with the incremented period. And if the previous task has become obsolete, make sure that you cancel() it.


For future reference, I recommend you utilize the Executors framework.

Submit another one task from run() if necessary:

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;



public class TimerTaskTest {

private static class MyTimerTask extends TimerTask {
    private final Timer timer;
    private boolean fire;

    private MyTimerTask(Timer timer) {
        this(timer, false);
    }

    private MyTimerTask(Timer timer, boolean fire) {
        this.timer = timer;
        this.fire = fire;
    }

    @Override
    public void run() {
        if (!fire) {
            System.out.println(new Date() + " - steady...");
            timer.schedule(new MyTimerTask(timer, true), 2000);
        } else {
            System.out.println(new Date() + " - go!");
        }
    }
}

public static void main(String args[]) {
    Timer timer = new Timer(true);
    MyTimerTask timerTask = new MyTimerTask(timer);

    System.out.println(new Date() + " - ready...");
    timer.schedule(timerTask, 4000);

    try {
        Thread.sleep(7000);
    } catch (Exception ignore) {
    }
}

}

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