2

I set up the TimerTask UpdateTask but it only fires once at the when I start my program. Why doesn't it continue to trigger?

Some of the methods here are in other classes, if you need them, don't hesitate to let me know.

import java.awt.Graphics;
import java.util.Timer;
import java.util.TimerTask;


public class graphpanel extends variables
{
Timer timer = new Timer();

int ypoint;
int barheight;

int height = getHeight();
int width = getWidth();
int bars = (int)getLife() - (int)getAge();
int xpoint = 0;
int barwidth = 20;

public graphpanel()
{
    timer.schedule(new UpdateTask(), 10);
}


public void paintComponent (Graphics g)
{
    super.paintComponent(g);

    for (int i = 0; i < bars; i++)
    {
        barheight = (int) getTime(i)/100;
        ypoint = height/2 - barheight;
        g.drawRect(xpoint, ypoint, barwidth, barheight);
        g.drawString("hey", 10*i, 40);
    }
}

class UpdateTask extends TimerTask
{
    public void run()
    {
        bars = (int)getLife() - (int)getAge();
        System.out.print("TimerTask detected");
        repaint();
    }
}

}

Christian Baker
  • 375
  • 2
  • 7
  • 22
  • Would Alarm Manager not be more appropriate? http://stackoverflow.com/questions/8679367/timer-task-vs-alarm-manager-usage-in-android-service – Submersed Dec 13 '13 at 21:05

2 Answers2

2

Timer.schedule(TimerTask, long) only schedules the task for one-time execution.

Use

timer.scheduleAtFixedRate(new UpdateTask(), 10, 10);

for repeating invocations of your TimerTask.

More info: JavaDoc

Stefan Winkler
  • 3,871
  • 1
  • 18
  • 35
0

You need to use

scheduleAtFixedRate(TimerTask task,Date firstTime,long period)

(or)

schedule((TimerTask task,Date firstTime,long period))

10 in your schedule() method call is delay, not period.

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167