Jim
Jim

Reputation: 19552

Schedule a periodic task dependent on result of previous run

I need to execute a task every X seconds.
I know that I could use a TimerTask or ScheduledThreadPool but my problem is that this task depends on state.
I.e. what the task will do in run B depends on what was the result of run A.
What would be the best approach to code this?
Doing perhaps a

while(true){  
  //do stuff  
  Thread.sleep(5000);  
}  

is the best I can do here?

Upvotes: 0

Views: 620

Answers (2)

user2030471
user2030471

Reputation:

I think you can use a Timer with a TimerTask:

Timer timer = new Timer();
TimerTask task = new TimerTask() {
    @Override
    public void run() {
        // Some task
    }
};
timer.schedule(task, 10000, 10000);

Which runs the task every 10s starting after an initial first time delay of 10s.

As per the documentation of Timer.schedule, this method

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

Upvotes: 1

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

Just define your state in your TimerTask implementation and then use Timer:

TimerTask task = new TimerTask ()
{
    private int state = 0;

    @Override
    public void run ()
    {
        System.out.println ("State is: " + state);
        state += 1;
    }
};

new Timer ().schedule (task, 0L, 1000L);

This will run task every second (every 1000L milliseconds) forever.

Upvotes: 2

Related Questions