Neo
Neo

Reputation: 391

Schedule a task to run at variable time interval

I am new to Java, Basically, I have to start a thread and run it at a default time interval say 100 seconds(comes from a variable cooldown). This cooldown can be updated any number of times. Suppose cooldown changes to 10 seconds, now the thread should run at intervals of 10 secs. What and how should I use to implement this? I looked into some options like ScheduledExecutorService but it takes a time interval which is not fixed in my case. A small example would be really helpful. Thanks.

Upvotes: 5

Views: 1705

Answers (2)

shmosel
shmosel

Reputation: 50716

Here's how you could do it with a TimerTask:

private volatile int cooldown = 100;
private Timer timer = new Timer();

private class MyTask extends TimerTask {
    @Override
    public void run() {
        // do work
        timer.schedule(new MyTask(), cooldown * 1000);
    }
}

private void startSchedule() {
    new MyTask().run();
}

public void setCooldown(int cooldown) {
    this.cooldown = cooldown;
}

Upvotes: 1

Erik
Erik

Reputation: 61

Encapsule the logic in a class and have a method that sets the interval. When the method is invoked you cancel the current scheduled task and starts a new one. It can look something like this:

private ScheduledExecutorService executorService = ...
private ScheduledFuture<T> future = null;

public void setCoolDown(int cooldownSec) {
    scheduleCoolDown(cooldownSec);
}

private synchronized void scheduleCoolDown(int interval) {
   if (future != null || !future.isDone()) {
        future.cancel();
   }
   future = executorService.scheduleAtFixedRate(theRunnable, interval, 0, TimeUnit.SECONDS);
}

The synchronized is there to make sure that only one thread can reschedule at the same time.

Upvotes: 2

Related Questions