(轉) java定時器的幾種用法

來源:互聯網
上載者:User

標籤:first   cond   instance   nbsp   定時器   imp   stat   四種   util   

 1 package com.lid; 2  3 import java.util.Calendar; 4 import java.util.Date; 5 import java.util.Timer; 6 import java.util.TimerTask; 7  8     // 第一種方法:設定指定任務task在指定時間time執行 schedule(TimerTask task, Date time) 9     public static void timer1() {10         Timer timer = new Timer();11         timer.schedule(new TimerTask() {12             public void run() {13                 System.out.println("-------設定要指定任務--------");14             }15         }, 2000);// 設定指定的時間time,此處為2000毫秒16     }17 18     // 第二種方法:設定指定任務task在指定延遲delay後進行固定延遲peroid的執行19     // schedule(TimerTask task, long delay, long period)20     public static void timer2() {21         Timer timer = new Timer();22         timer.schedule(new TimerTask() {23             public void run() {24                 System.out.println("-------設定要指定任務--------");25             }26         }, 1000, 1000);27     }28 29     // 第三種方法:設定指定任務task在指定延遲delay後進行固定頻率peroid的執行。30     // scheduleAtFixedRate(TimerTask task, long delay, long period)31     public static void timer3() {32         Timer timer = new Timer();33         timer.scheduleAtFixedRate(new TimerTask() {34             public void run() {35                 System.out.println("-------設定要指定任務--------");36             }37         }, 1000, 2000);38     }39    40     // 第四種方法:安排指定的任務task在指定的時間firstTime開始進行重複的固定速率period執行.41     // Timer.scheduleAtFixedRate(TimerTask task,Date firstTime,long period)42     public static void timer4() {43         Calendar calendar = Calendar.getInstance();44         calendar.set(Calendar.HOUR_OF_DAY, 12); // 控制時45         calendar.set(Calendar.MINUTE, 0);       // 控制分46         calendar.set(Calendar.SECOND, 0);       // 控制秒47 48         Date time = calendar.getTime();         // 得出執行任務的時間,此處為今天的12:00:0049 50         Timer timer = new Timer();51         timer.scheduleAtFixedRate(new TimerTask() {52             public void run() {53                 System.out.println("-------設定要指定任務--------");54             }55         }, time, 1000 * 60 * 60 * 24);// 這裡設定將延時每天固定執行56     }57 }

 

(轉) java定時器的幾種用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.