问题
I need to autoSend reports to my clients at perticular timings like
- every day at 00:01 AM
- every Week at Sunday 00:01 AM
- on day 1 of every month
- on day 1 of every year
For every day i am doing this :
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("context initiallized");
System.out.println("Starting timer");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
Date alarmTime = calendar.getTime();
_timer = new Timer();
_timer.schedule(new AlarmTask(), alarmTime);
}
Here is the class where i perform my everyday task :
public class AlarmTask extends TimerTask {
public void run() {
// Do your work here; it's 00:01 AM!
}
}
It seems to work fine BUT when i start tomcat at anytime after 00:01 AM Say at 02:30 AM the task is performed as soon as the context is loaded where i need it to be performed on next day...
Is their any problem with my code ?
回答1:
Calendar
models the full date so you have scheduled in the past. Timer
will respond to that by executing immediately. Increment the day on the Calendar
.
回答2:
Why don't you use QuartzSchedular http://quartz-scheduler.org/
回答3:
Have you looked at Quartz ? It could help you schedule your tasks!
回答4:
I guess u will have to do what Marko Topolnik said above https://stackoverflow.com/a/14781326/2040095
but in addition do u also need to invoke the 3 parameters form of method "schedule" for Timer class since you need this report to be send every day and not just one day ?
So something like
_timer.schedule(new AlarmTask(), alarmTime, period );
where period would be a 24 hours for daily reports.
回答5:
If you are doing this in a huge projects I prefer you to go to Quartz Schedular since It has a user interface to handle jobs and create and edit jobs. If it is just a small alarm task that has to executed periodically crate a batch file and add that to chron job to run in specific intervals.
Hope this will help..
来源:https://stackoverflow.com/questions/14781296/calling-a-method-every-day-every-week-every-month-and-every-year