jdk自帶三種定時(shí)任務(wù)實(shí)現(xiàn)方式
1 Thread
public class Demo01 {
static long count = 0;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
count++;
System.out.println(count);
} catch (Exception e) {
// TODO: handle exception
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
2 java.util.TimeTask
public class Demo02 {
static long count = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
count++;
System.out.println(count);
}
};
Timer timer = new Timer();
// 天數(shù)
long delay = 0;
// 秒數(shù)
long period = 1000;
timer.scheduleAtFixedRate(timerTask, delay, period);
}
}
3 java.util.concurrent.ScheduledExecutorService
public class Demo003 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
// task to run goes here
System.out.println("Hello !!");
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
// 第二個(gè)參數(shù)為首次執(zhí)行的延時(shí)時(shí)間赏胚,第三個(gè)參數(shù)為定時(shí)執(zhí)行的間隔時(shí)間
service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);
}
}
定時(shí)任務(wù)框架Quarts
引入jar包肾扰,按官方教程編程即可
分布式定時(shí)任務(wù)xxl-job
github開(kāi)源分布式任務(wù)調(diào)度框架
① 部署: xxl-job-admin 作為注冊(cè)中心
② 創(chuàng)建執(zhí)行器(具體調(diào)度地址) 可以支持集群
③ 配置文件需要填寫(xiě)xxl-job注冊(cè)中心地址
④ 每個(gè)具體執(zhí)行job服務(wù)器需要?jiǎng)?chuàng)建一個(gè)netty連接端口號(hào)
⑤ 需要執(zhí)行job的任務(wù)類蚯根,集成IJobHandler抽象類注冊(cè)到j(luò)ob容器中
⑥ Execute方法中編寫(xiě)具體job任務(wù)