Rydberg1995
Rydberg1995

Reputation: 49

Using timer.schedule for repeating a method

I'm trying to make an application that is kind of a counter. However, I'm trying to make kind of an income so that the application counts itself.

class Income extends TimerTask {

    @Override
    public void run() {
        CowCount = CowCount + income;
    }

}

Timer timer = new Timer();
timer.schedule(new Income(), 1000);

This is how it looks so far. It doesn't work, though. At timer.schedule, the dot in between is seen as an error, the first parenthesis and the second parenthesis after "Income" at the same line. In this question, it seems like that I'm doing the right thing.

And one last thing: Will this timer continue to run even if I'm starting to run other methods? If it stops I think I need to find another way.

EDIT: These are the errors: 1. Syntax error on token(s), misplaced construct(s) 2. Syntax error on token "(", = expected 3. Syntax error on token ")", invalid arguments list.

The first error is at the dot between timer and schedule The second error is on the parenthesis after schedule . The third error is on the second parenthesis after "Income" at the last line of code.

Upvotes: 2

Views: 4068

Answers (1)

Sage
Sage

Reputation: 15408

Make sure that you are using java.util.Timer class. And if you are doing so, then something tells me that:

Timer timer = new Timer();
timer.schedule(new Income(), 1000);

these code is out of any class context. You need to do this inside of class member function or inside the constructor. For example:

public class checkTimer extends TimerTask{

   int counter = 0;


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


    @Override
    public void run() {
       counter++;
        System.out.println(counter); // use logCat to see
    }
}

And one last thing: Will this timer continue to run even if I'm starting to run other methods? If it stops I think I need to find another way.

The timer will run but you are using timer.schedule(new Income(), 1000); which is actually schedule(TimerTask, delay). It will run for once after the defined delay time. For repeated task, You will need to use-

schedule (TimerTask task, long delay, long period)

function. Where period is the amount of time in milliseconds between subsequent executions.

Upvotes: 3

Related Questions