定时任务 ScheduledExecutorService
生活随笔
收集整理的這篇文章主要介紹了
定时任务 ScheduledExecutorService
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;
/**
* ScheduledExecutorService是從Java SE 5的java.util.concurrent里,做為并發工具類被引進的,這是最理想的定時任務實現方式。
* 相比于上兩個方法(普通thread和用Timer、TimerTask),它有以下好處:
* 相比于Timer的單線程,它是通過線程池的方式來并發執行任務的
* 可以很靈活的去設定第一次執行任務delay時間
* 提供了良好的約定,以便設定執行的時間間隔
*/
public class Timer implements Runnable {
private String something;
private int index = 0;
public Timer(String something) {
this.something = something;
}
@Override
public void run() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if("beautiful".equals(something)) {
if (index == "beautiful".length()) {
System.out.println();
System.out.println(df.format(new Date()) + " " + "beautiful!!!");
index = 0;
} else {
if (index == 0)
System.out.print(df.format(new Date()) + " ");
System.out.print("beautiful".charAt(index));
index++;
}
}else{
System.out.println(df.format(new Date())+" "+something);
}
}
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
System.out.println(df.format(new Date())+" you are");
long initialDelay1 = 1;
//從現在開始1秒鐘之后,只執行一次
service.schedule(new Timer("... ..."), initialDelay1,TimeUnit.SECONDS);
long initialDelay2 = 2; //延遲
long period2 = 1; //間隔
// 從現在開始2秒鐘之后,每隔1秒鐘執行一次
// scheduleAtFixedRate 每隔固定的時間,立即執行下一次。(scheduleWithFixedDelay 等上一次任務執行完畢,才會執行下一次)
service.scheduleAtFixedRate(new Timer("beautiful"),initialDelay2, period2, TimeUnit.SECONDS);
}
}
結果:
2018-09-19 14:01:52 you are 2018-09-19 14:01:53 ... ... 2018-09-19 14:01:54 beautiful 2018-09-19 14:02:03 beautiful!!! 2018-09-19 14:02:04 beautiful 2018-09-19 14:02:13 beautiful!!!
。。。
總結
以上是生活随笔為你收集整理的定时任务 ScheduledExecutorService的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 移动应用测试—— 测试用例设计示例
- 下一篇: 钉钉静默安装