按时间间隔执行

来源:互联网 发布:淘宝如何拍下商品 编辑:程序博客网 时间:2024/04/29 02:41

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

public  class FetchMail extends TimerTask {

  /**
  * Construct and use a TimerTask and Timer.
  */

  /**
  * Implements TimerTask's abstract run method.
  */
  public void run(){
    //toy implementation
    time=time+1;
    System.out.println(time);
  }

  // PRIVATE ////
  private static int time=1;
  //expressed in milliseconds
  //private final static long fONCE_PER_DAY = 1000*60*60*24;
  private final static long fONCE_PER_DAY = 1000*2;
  private final static int SECOND = 3;
  private final static int fONE_DAY = 1;
  private final static int fFOUR_AM = 4;
  private final static int fZERO_MINUTES = 0;

  private static Date getTomorrowMorning4am(){
    Calendar tomorrow = new GregorianCalendar();
    //tomorrow.add(Calendar.DATE, fONE_DAY);
    tomorrow.add(Calendar.SECOND,fONE_DAY);
    Calendar result = new GregorianCalendar(
      tomorrow.get(Calendar.YEAR),
      tomorrow.get(Calendar.MONTH),
      tomorrow.get(Calendar.DATE),
      fFOUR_AM,
      fZERO_MINUTES
    );
    System.out.println("11");
    return tomorrow.getTime();
  }

 /**
  * Method main
  *
  *
  * @param args
  *
  */
 public static void main(String[] args) {
  // TODO: Add your code here
      TimerTask fetchMail  = new FetchMail();
    Calendar tomorrow = new GregorianCalendar();
    //tomorrow.add(Calendar.DATE, fONE_DAY);
    tomorrow.add(Calendar.SECOND, SECOND);
    System.out.println(tomorrow.getTime());
    Calendar tomorrow1 = new GregorianCalendar();
    //tomorrow.add(Calendar.DATE, fONE_DAY);
    tomorrow1.add(Calendar.SECOND, SECOND+2);
   
    System.out.println(tomorrow1.getTime());
    //perform the task once a day at 4 a.m., starting tomorrow morning
    //(other styles are possible as well)
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(fetchMail, getTomorrowMorning4am(), fONCE_PER_DAY);
 }

原创粉丝点击