本文介绍了每天,每周,每月和每年调用一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在特定时间自动向我的客户发送报告




  • 每天凌晨00:01

  • 每个星期天的上午00:01

  • 在每月的第一天

  • 在每年的第一天



我每天都在这样做:

  public void contextInitialized(ServletContextEvent arg0){

System.out.println( context initiallized);
System.out.println(启动计时器);

日历日历= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,1);
calendar.set(Calendar.SECOND,0);

日期AlarmTime = calendar.getTime();

_timer = new Timer();
_timer.schedule(new AlarmTask(),alarmTime);
}

这是我执行日常任务的班级:

 公共类AlarmTask扩展了TimerTask {

public void run(){
//在这里工作;现在是00:01!
}
}

但效果很好 当我在凌晨00:01之后任何时候启动tomcat时说在凌晨02:30,任务会在上下文加载后立即执行,而我需要在第二天执行...... b

我的代码有问题吗?

解决方案

日历为整个日期建模,因此您可以安排过去的日期。 Timer 将通过立即执行来响应。在日历上增加一天。


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 ?

解决方案

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.

这篇关于每天,每周,每月和每年调用一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:00