一、线程等待(不建议使用,任务复杂时存在内存泄露风险)
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("TestThreadWait is called!");
try {
// 使用线程休眠来实现周期执行
Thread.sleep(1000 * 3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
myThread.start();
二、Timer
package com.changan.test;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
/*Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("执行定时任务");
}
},1000,1000);*/
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("TimerTask is called!");
}
};
Timer timer = new Timer();
/*
* schedule 和 scheduleAtFixedRate 区别:
* 可将schedule理解为scheduleAtFixedDelay,
* 两者主要区别在于delay和rate
* 1、schedule,如果第一次执行被延时(delay),
* 随后的任务执行时间将以上一次任务实际执行完成的时间为准
* 2、scheduleAtFixedRate,如果第一次执行被延时(delay),
* 随后的任务执行时间将以上一次任务开始执行的时间为准(需考虑同步)
*
* 参数:1、任务体 2、延时时间(可以指定执行日期)3、任务执行间隔时间
*/
// timer.schedule(task, 0, 1000 * 3);
timer.scheduleAtFixedRate(task, 0, 1000 * 3);
}
}
三、ScheduledExecutorService
package com.changan.test;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
System.out.println("ScheduledExecutorService Task is called!");
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
// 参数:1、任务体 2、首次执行的延时时间
// 3、任务执行间隔 4、间隔时间单位
service.scheduleAtFixedRate(runnable, 0, 3, TimeUnit.SECONDS);
}
}
四、@Scheduled
1、配置
在spring boot的启动类上加@EnableScheduling注解,允许支持@Scheduled:
@SpringBootApplication
@EnableScheduling
public class Quartz01Application {
public static void main(String[] args) {
SpringApplication.run(Quartz01Application.class, args);
}
}
2、任务类
@Component
public class ScheduleTask {
// 每隔5秒执行一次
@Scheduled(cron = "0/5 * * * * ?")
public void printSay() {
System.out.println("每隔5秒执行一次:" + new Date());
}
}