使用TimerTask做每月定时执行任务.

  • Post author:
  • Post category:其他

/**
 * <p>Title: SubBillingTimer </p>
 * <p>Description:概要说明:设置定时发送包月计费包.

                  部分属性变量的解释:
                 
                  部分函数/方法的解释:
                  1.setTimer()   设置执行任务时的特定时间._timer.schedule(new SubBillingTimer(), date);
                  2.subBilling() 绑定计费包并发送.
                  3.run() 到已经特定的时间就执行,并调用subBilling(),然后在调用setTimer()设置下个月的特定时间
                 
 */

import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;
import java.util.Timer;

public class SubBillingTimer extends TimerTask {
  private Timer _timer;
  private int _day = 21;
  private int _hour = 2;

  public SubBillingTimer() {
   
  }

  public void run() {
 
    if(initConfigure.DEBUG_LEVEL > 8) {
     
 
      System.out.println(” — Sub Billing Timer start run…”);
    }
 
    subBilling();
    setTimer(_day, _hour, true);
  }

  public void setTimer(int day, int hour) {
    setTimer(day, hour, false);
  }

  public void setTimer(int day, int hour, boolean bgNextMonth) {
    _day = day;
    _hour = hour;

    Calendar cale = Calendar.getInstance();//Gets a calendar using the default time zone and locale.
    if(bgNextMonth || cale.get(cale.DAY_OF_MONTH) >= day) {//超过这个天数或者下个月为真,就是设定时间任务为下个月
      cale.set(cale.MONTH, cale.get(cale.MONTH) + 1);
    }
    Date date = new Date(cale.get(cale.YEAR) – 1900, cale.get(cale.MONTH), day, hour, 0);
    if(_timer == null) {
      _timer = new Timer();
    }
      System.out.println(“Set SubBilling Timer[“+date+”:”+(date.getTime() – System.currentTimeMillis())+”]: ” + _timer.toString());
  
    _timer.schedule(new SubBillingTimer(), date);//Schedules the specified task for execution at the specified time.设定时间
  }

  public void stop() {
    this.cancel();
    _timer.cancel();
  }

  private void subBilling() {
   }

  public static void main(String[] args) {
    SubBillingTimer sub_timer = new SubBillingTimer();
    sub_timer.setTimer(21, 2);
  }
}


版权声明:本文为yizdream原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。