This is a little snippet of code I wrote for destroying an object in a game I’m working on with pals. See the comments in the code for an explanation. I used currentTimeMillis(); just to check that the code was working as it should, and left it in for demonstration purpose. The output is:

Baddie hits wall, start timer: 
Baddie is dead!
Time Taken: 3000
BUILD SUCCESSFUL (total time: 3 seconds)

Of course, the above output will not display in the game, the action will be represented with an animated ‘Sprite’ of some sort meeting a grizzly death.

* This program will be attached to a game character, the 'Baddie'.
* When Baddie collides with a wall, he hangs around for 3 seconds (roughly)
* then he dies.
* This program is the timer delay logic used to destroy the character.

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

public class TimerDelayTask {
static Timer timer;
static TimerTask TimerTask;
static long startTime = 0L;
static long elapsedTime = 0L;
static int seconds = 0;

public TimerDelayTask(int seconds) {
timer = new Timer();
timer.schedule(new Reminder(), seconds * 1000);
startTime = System.currentTimeMillis();
//inner class

class Reminder extends TimerTask {

public void run() {
System.out.println("Baddie is dead!");
System.out.print("Time Taken: ");
System.out.println(elapsedTime = System.currentTimeMillis() - startTime);

public static void main(String[] args) {
new TimerDelayTask(3);
System.out.println("Baddie hits wall, start timer: ");