分布式任务调度平台XXL-JOB
什么是定时任务?
指定时间去执行任务
Java实现定时任务方式?
1.Thread br/>2.timerTask
3.springboot中@Scheduled注解
4.线程池中ScheduledExecutorService 定时线程
5.Quartz
一.Thread
public class Demo01 {
static long count = 0;
public static void main(String[] args) {
Runnable runnable = new Runnable() {br/>@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();
}
}
二.TimerTask
/**
-
使用TimerTask类实现定时任务
*/
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(); // 天数 long delay = 0; // 秒数 long period = 1000; timer.scheduleAtFixedRate(timerTask, delay, period);
}
}
三.ScheduledExecutorService
使用ScheduledExecutorService是从Java
JavaSE5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。
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();
// 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);
}
}
四.Quartz
创建一个quartz_demo项目
引入maven依赖
<dependencies>