該類需要導入包
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
一、使用scheduleAtFixedRate()方法實現週期性執行
public class ScheduledExecutorServiceTest {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("run "+ System.currentTimeMillis());
}
}, 0, 100, TimeUnit.MILLISECONDS);
}
}
每隔100毫秒,執行一次run任務,得到執行後的打印:
run 1501051231331
run 1501051231427
run 1501051231527
run 1501051231628
run 1501051231726
run 1501051231827
run 1501051231926
run 1501051232026
run 1501051232127
.......
接口scheduleAtFixedRate原型定義及參數說明
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
command:執行線程
initialDelay:初始化延時
period:兩次開始執行最小間隔時間
unit:計時單位
接口scheduleWithFixedDelay原型定義及參數說明
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
command:執行線程
initialDelay:初始化延時
period:前一次執行結束到下一次執行開始的間隔時間(間隔執行延遲時間)
unit:計時單位
週期定時執行某個任務。
有時候我們希望一個任務被安排在凌晨3點(訪問較少時)週期性的執行一個比較耗費資源的任務,可以使用下面方法設定每天在固定時間執行一次任務。
/**
* 每天晚上8點執行一次
* 每天定時安排任務進行執行
*/
public static void executeEightAtNightPerDay() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
long oneDay = 24 * 60 * 60 * 1000;
long initDelay = getTimeMillis("20:00:00") - System.currentTimeMillis();
initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
executor.scheduleAtFixedRate(
new EchoServer(),
initDelay,
oneDay,
TimeUnit.MILLISECONDS);
}
/**
* 獲取指定時間對應的毫秒數
* @param time "HH:mm:ss"
* @return
*/
private static long getTimeMillis(String time) {
try {
DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
return curDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}