Sometimes in Processing you want to do something with a certain rhythm, and you don’t feel like writing something like this:

long m = millis();

void draw() {
   if (millis() - m > 1000) {
       m = millis();
       println("wow!");
   }
}

What you really want is a true timer, something that calls a part of your program every n milliseconds.

Well, Java has just such a Timer and it’s not all that hard to use. If you look at the class (link), you’ll see that you have just a few methods that deal with setting how often your timer needs to go off, cancelling your timer, and maybe one or two other things. The hard part (which isn’t really all that hard if you read understood my recent post about Polymorphism) is actually setting up the Timer using the extends syntax.

Bascially, you have to create some class that is going to be called periodically, and then inform Java that this class is going to act like a TimerTask. This is the role of the « extends » keyword. The syntax is as follows:

class Beat extends TimerTask {

    Timer timer;

    Beat() {
       timer = new Timer();
       timer.scheduleAtFixedRate(this, 0, 1000);
    }

    // careful! something's missing here

}

If you try to run the following code, Processing/Java will yell at you. Hey you idiot! You forgot to tell me what I’m supposed to do every 1000 milliseconds! A TimerTask needs to implement a method that will be called whenever the Timer fires. Since we’ve extended the TimerTask class, Java knows that this object has to contain a method named « run() » in order to work. It knows as such because when you pushed the “play” button, it went to look inside the definition of the abstract class « TimerTask », where it is explained that all TimerTask objects have to include a « run() » method.

Here’s the completed class:

class Beat extends TimerTask {

  Timer timer;

  Beat() {
    timer = new Timer();
    timer.scheduleAtFixedRate(this, 0, 1000);
  }

  void run() {
    // do something here
  }

}

Now that the run() method has been declared, the rest is easy to explain. The « sheduleAtFixedRate » method is pretty easy to understand. If you write it this way, it just means « after waiting 0 milliseconds before starting, call « this » object’s run() method every 1000 milliseconds ».

Here’s a dopey little animation to show you how it might work:

Beat beat;

void setup() {
  smooth();
  beat = new Beat();
}

void draw() {
  beat.draw();
}

void mousePressed() {
  beat.die();
}

class Beat extends TimerTask {

  Timer timer;

  int alfa = 0;
  int speed = 5;

  Beat() {
    timer = new Timer();
    timer.scheduleAtFixedRate(this, 0, 1000);
  }

  void run() {
    alfa = 255;
  }

  void die() {
    timer.cancel();
  }

  void draw() {
    background(255);
    noStroke();
    fill(0,alfa);
    ellipse(width/2, height/2, 10, 10);
    alfa = max(alfa-speed, 0);
  }

}