I'm trying to run a method once a week. For example, every Monday 8pm. I use this code:
Timer timer = new Timer();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
Date time = calendar.getTime();
timer.schedule(new PrintTask(),
time);
// other code where variable gets increased
public class PrintTask extends TimerTask {
public void run() {
variable = 0;
}
}
However, if I am right, the dosomething
code is run continuously - as long as the calendar time has already passed. For example, now it has already been Monday, so the dosomething
code is run all the time. A variabele gets increased, but it must be reset to 0 on Monday. The variable is now constantly 0, because it is reset again and again. If I use calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
, the variable is not reset, because it has not been Sunday yet. But as soon as it is Sunday 8pm, he will probably continue to reset the rest of that day.
I want the dosomething
code to be executed only once at the one time specified. Can someone tell me how to adjust the code to achieve this?
Sorry for my English