Creating a generic task in Java using a timer

In an Android game, I ask the player a question and I want to give different hints after different lengths of time, and finally give the answer, if the player fails to answer in time.

The questions, the hints and the delay times are read in from an external file, in JSON format.

I would like to set up a timer for each hint. In JavaScript I could do create a generic method with a closure, something like this:

JavaScript Code

<body>
<p id="1">One</p>
<p id="2">Two</p>
<p id="3">Three</p>

<script>
var hints = [
  { id: 1, delay: 1000, text: "Hint 1" }
, { id: 2, delay: 2000, text: "Hint 2" }
, { id: 3, delay: 3000, text: "Hint 3" }
]

hints.map(setTimeoutFor)

function setTimeoutFor(hint) {
  setTimeout(showHint, hint.delay)

  function showHint() {
    element = document.getElementById(hint.id)
    element.innerHTML = hint.text
  }
}
</script>

In Java, I know that I can use a separate method for each hint, like this:

Java Code

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

String hint1 = "foo";
CustomType location1 = customLocation;
Timer timer1;
TimerTask task1;

void createTimer1(delay) {
    timer1 = new Timer();
    task1 = new TimerTask() {
        @Override
        public void run() {
            giveHint1();
        }
    };
    timer1.schedule(task1, delay);
}

void giveHint1() {
  timer1.cancel()
  giveHint(hint1, location1);
}

void giveHint(String hint, CustomType location) {
  // Code to display hint at the given location
}

This is not elegant. What techniques can I use in Java to make this generic, so that I can use the same method for all hints?

Answer

Why would you need a separate method for each hint? You can use method arguments, like this:

// "final" not required in Java 8 or later
void createTimer(int delay, final String hint, final Point location) {
    timer = new Timer();
    task = new TimerTask() {
        @Override
        public void run() {
            giveHint(hint, location);
        }
    };
    timer.schedule(task, delay);
}

void giveHint(String hint, CustomType location) {
  // Code to display hint at the given location
}

Leave a Reply

Your email address will not be published. Required fields are marked *