目录
2、使用第三方包:QuartZ ---- 适合特别复杂的业务
3、使用 Spring 自带的定时任务管理 ----一般情况会用这个就够了
1、JDK 自带 的 TimerTask
【了解】 https://www.cnblogs.com/0201zcr/p/4703061.html
For Example:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println("11232");
}
}, 2000 , 1000);
2s后开始执行,每秒执行一次
2、使用第三方包:QuartZ
【熟悉,单个类测试通过,但集成到SSM/SpringBoot 还没研究成功】
https://www.w3cschool.cn/quartz_doc/
For Example:
(1)、导入 POM 依赖:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.3.0</version>
</dependency>
(2)、工具类 QuartzManager
public class QuartzManager {
private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory(); //创建一个SchedulerFactory工厂实例
private static String JOB_GROUP_NAME = "JOB_GROUP_1"; //任务组
private static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_1"; //触发器组
/**
*添加一个定时任务,
*/
public static void addJob(String jobName, Class<? extends Job> cls, String time) {
try {
Scheduler sched = gSchedulerFactory.getScheduler();
JobDetail jobDetail= JobBuilder.newJob(cls).withIdentity(jobName,JOB_GROUP_NAME).build();
CronTrigger trigger = (CronTrigger) TriggerBuilder
.newTrigger()
.withIdentity(jobName, TRIGGER_GROUP_NAME)
.withSchedule(CronScheduleBuilder.cronSchedule(time))
.build();
sched.scheduleJob(jobDetail, trigger);
if (!sched.isShutdown()) {
sched.start(); // 启动
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
(3)、Job 类 HelloJob
public class HelloJob implements Job {
public HelloJob() {
}
public void execute(JobExecutionContext context) throws JobExecutionException
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Hello! HelloJob is executing."+df.format(new Date()));
}
}
(4)、测试类 testQuartZ
public class testQuartZ {
public static void main(String[] args) throws HttpException, IOException {
QuartzManager.addJob("Demo", HelloJob.class, "0/5 * * * * ?");
}
}
(5)、运行测试类,效果如下
3、使用 Spring 自带的定时任务管理
【正在使用当中】
3.1、 SSM 之 Spring 实现定时任务
3.2、SpringBoot 注解实现定时任务 (基于 SpringBoot 2.X)
(1)启动类添加注解 @EnableScheduling
(2)类上添加注解 @Component 被容器扫描
(3)需要定时执行的方法添加注解 @Scheduled(fixedRate = 2000) 每2秒执行一次
@Component
public class testTask {
@Scheduled(fixedRate = 2000)
public void test(){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Hello! HelloJob is executing."+df.format(new Date()));
}
}