How to run 2 timers on the same TimerTask at different delays in Java.

Lets say you want to run a process on a timer at a random time between 0-5 minutes, but then once that process is complete, you want to run the same process again after 5 minutes?  I have a easy solution for you to try out. All you will use is the java.util.Timer and TimerTask libraries.

1. Create a class that extends TimerTask, in this case I will create TestTimerTask.java.

2. Add the following code. We are creating a Timer property that we will pass into the constructor. Then we create a startTimer method that will purge the prior task, then schedule a new task in 5 minutes (300000 ms) with a new instance of TestTimerTask and Timer.  Once run is complete, startTimer is called, and will execute the same run method in approximately 5 minutes.


import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimerTask extends TimerTask {

    Timer timer;

    public TestTimerTask(Timer timer){
        this.timer = timer;
    }

    public void startTimer(){
        this.timer.purge();
        timer = new Timer();
        timer.schedule(new TestTimerTask(timer), 300);
    }

    @Override
    public void run() {
        try{
            Thread.sleep(500);
        } catch (Exception e) {
            e.printStackTrace();
        }
        startTimer();
    }
}

3. In your main method, create a Timer instance and TestTimerTask instance and pass in a new timer. Then schedule a task with a random time between 0-5 mins (0-600000ms).
This is a quick and easy solution that will help you solve the problem above. I tried other solutions but could not accomplish my scenario. If anyone has a cleaner solution please let me know in the comments below!

import java.util.Random;
import java.util.Timer;

public class Main {

    public static void main(String[] args) {
        Timer timer = new Timer();
        TestTimerTask task = new TestTimerTask(timer);
        timer.schedule(task, new Random().nextInt(600000));
    }
}