Reputation: 9
I have a requirement for a web project to build a reminder that display a message for the input date and time. I don't want to use any plugins or jar files. I came up with the code and there is an error in timer.schedule(task,date);
I'm also new to java and don't know if this is the right approach.
Code:
public String reminder(Model model, HttpServletRequest req, HttpServletResponse res) throws ParseException
{
String myDate = "2012-06-09 17:43:20";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date)formatter.parse(myDate);
TimerTask task = YoTimes(model);
Timer timer = new Timer();
timer.schedule(task,date);
return "/view";
}
private TimerTask YoTimes(Model model)
{
model.addAttribute("timerMsg", "Yo Timer");
return null;
}
EDIT
Stacktrace:
ERROR:java.lang.NullPointerException
at java.util.Timer.sched(Unknown Source)
at java.util.Timer.schedule(Unknown Source)
Upvotes: 0
Views: 1206
Reputation: 7522
Your YoTimes
method returns null
. It should return an instance of java.util.TimerTask
, so that you can pass it to Timer#schedule(TimerTask, Date)
.
The edited yoTimes
method (note that as a best practice / convention, Java methods should start with a lowercase character):
private TimerTask yoTimes(Model model) {
model.addAttribute("timerMsg", "Yo Timer");
return new MyTimerTask();
}
The newly created MyTimerTask
class:
public class MyTimerTask extends TimerTask {
public void run() {
// Whatever the task should be
}
}
Upvotes: 2
Reputation: 285460
private TimerTask YoTimes(Model model)
{
model.addAttribute("timerMsg", "Yo Timer");
return null; // ************
}
Please look at what you're returning here!
No surprise then that this will cause a NPE. Perhaps you want to return an actual TimerTask object. ;-)
So instead create and return your TimerTask:
private TimerTask YoTimes(final Model model)
{
model.addAttribute("timerMsg", "Yo Timer");
return new TimerTask() {
public void run() {
// whatever code you want called by the timer
}
};
}
Upvotes: 2