Java實現定時器的四種方式


  • package com.wxltsoft.tool;
  •  
     
  •  
    import org.junit.Test;
  •  
     
  •  
    import java.util.Calendar;
  •  
    import java.util.Date;
  •  
    import java.util.Timer;
  •  
    import java.util.TimerTask;
  •  
     
  •  
    /**
  •  
    * @Author: Zhangbx
  •  
    * @Description:
  •  
    * @Date: 2017/12/5
  •  
    * @Modified By:
  •  
    * @Modified Date:
  •  
    */
  •  
    public class TimerUtil {
  •  
     
  •  
    public static void main(String[] args) {
  •  
    // timer1();
  •  
    // timer2();
  •  
    // timer3();
  •  
    timer4();
  •  
    }
  •  
     
  •  
    /**
  •  
    * 設定2000毫秒后執行
  •  
    */
  •  
    public static void timer1(){
  •  
    Timer nTimer = new Timer();
  •  
    nTimer.schedule( new TimerTask() {
  •  
    @Override
  •  
    public void run() {
  •  
    System.out.println( "----設定要指定任務-----");
  •  
    }
  •  
    }, 2000);
  •  
    }
  •  
     
  •  
    /**
  •  
    * 延遲5000毫秒,每1000毫秒執行一次
  •  
    */
  •  
    public static void timer2() {
  •  
    Timer timer = new Timer();
  •  
    timer.schedule( new TimerTask() {
  •  
    public void run() {
  •  
    System.out.println( "-------延遲5000毫秒,每1000毫秒執行一次--------");
  •  
    }
  •  
    }, 5000, 1000);
  •  
    }
  •  
     
  •  
    /**
  •  
    * 延遲5000毫秒,每1000毫秒執行一次
  •  
    */
  •  
    public static void timer3() {
  •  
    Timer timer = new Timer();
  •  
    timer.scheduleAtFixedRate( new TimerTask() {
  •  
    public void run() {
  •  
    System.err.println( "-------延遲5000毫秒,每1000毫秒執行一次--------");
  •  
    }
  •  
    }, 5000, 1000);
  •  
    }
  •  
    /**
  •  
    * 設置17:56執行任務
  •  
    * java.util.Timer.scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
  •  
    */
  •  
    public static void timer4() {
  •  
    Calendar calendar = Calendar.getInstance();
  •  
    calendar.set(Calendar.HOUR_OF_DAY, 17);
  •  
    calendar.set(Calendar.MINUTE, 26);
  •  
    calendar.set(Calendar.SECOND, 0);
  •  
     
  •  
    Date time = calendar.getTime();
  •  
     
  •  
    Timer timer = new Timer();
  •  
    timer.scheduleAtFixedRate( new TimerTask() {
  •  
    public void run() {
  •  
    System.out.println( "-------設定要指定任務--------");
  •  
    }
  •  
    }, time, 1000 * 60 * 60 * 24);// 這里設定將延時每天固定執行
  •  
    }
  •  
     
  •  
     
  •  
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM