定时任务框架很多种Quartz,SpringTask,xxljob,PowerJob...
1、JDK提供的timer
// JDK提供的
Timer timer = new Timer();
//timer.schedule(new TimerTask() {
// @Override
// public void run() {
// System.out.println("JDK提供的 timer task 执行了~");
// }
//},0);
// 指定时间执行,并且两秒执行一次
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("JDK提供的 timer task 执行了~");
}
}, new Date(), 2000);
2、Quartz
先导入依赖
implementation 'org.springframework.boot:spring-boot-starter-quartz:3.0.2'
定义一个你需要执行的任务
package com.qbb.quartz;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
/**
* @author startqbb (个人博客:https://www.cnblogs.com/qbbit)
* @date 2023-02-08 20:56
* @tags 喜欢就去努力的争取
*/
@Slf4j
public class QuartzBean extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
log.info("quartz task run ......");
}
}
定义一个Quartz的配置类,绑定Trigger和JobDetail
package com.qbb.quartz;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author startqbb (个人博客:https://www.cnblogs.com/qbbit)
* @date 2023-02-08 20:57
* @tags 喜欢就去努力的争取
*/
@Configuration
public class QuartzConfig {
@Bean
public JobDetail jobDetail() {
// 绑定Job
return JobBuilder
.newJob(QuartzBean.class)
.storeDurably()
.build();
}
@Bean
public Trigger trigger() {
// 绑定JobDetail
ScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
return TriggerBuilder
.newTrigger()
.forJob(jobDetail())
.withSchedule(scheduleBuilder)
.build();
}
}
启动主程序
3、SpringTask
开启SpringTask定时任务
package com.qbb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling // 开启定时任务
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
在需要执行的任务上加@Scheduled
(注意需要把当前任务类交给Spring管理)
package com.qbb.springtask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author startqbb (个人博客:https://www.cnblogs.com/qbbit)
* @date 2023-02-08 21:10
* @tags 喜欢就去努力的争取
*/
@Component
@Slf4j
public class SpringTaskDemo {
@Scheduled(cron = "0/1 * * * * ?")
public void print(){
log.info("SpringTask Run ......");
}
}