-1

Timer does not start, is the null return type wrong. Or the return type must be new timertask.

package testing;
import java.util.Timer;
import java.util.TimerTask;

public class myClass {
    public static TimerTask run() {
        System.out.println("hello.");
        return null;
    }
    public static void setTimer(int seconds) {
        Timer timerObject = new Timer();
        timerObject.scheduleAtFixedRate(run(), 0, 1000);
    }
    public static void main(String args[]) {
        setTimer(1);
    }
}
bzix
  • 19
  • 1
  • 3
    If you want to execute a timer task you probably need to actually create a timer task. – khelwood May 19 '21 at 13:10
  • 1
    return null will do that for you – Stultuske May 19 '21 at 13:12
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Stultuske May 19 '21 at 13:14
  • You are currently expecting `run()` to be the `TimerTask` , but `run` is supposed to return an instance of `TimerTask`. – f1sh May 19 '21 at 13:16

1 Answers1

1

You have to assign TimerTask object to scheduleAtFixedRate function, your run function is returning null, not TimerTask object.

package testing;
import java.util.Timer;
import java.util.TimerTask;

public class myClass {
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            System.out.println("hello.");
        }
    };
    public static void setTimer(int seconds) {
        Timer timerObject = new Timer();
        timerObject.scheduleAtFixedRate(task, 0, 1000);
    }
    public static void main(String args[]) {
        setTimer(1);
    }
}
CooderSK
  • 147
  • 1
  • 2
  • 8