java---20

目录

一 Springboot整合Scheduled

1、导入Scheduled依赖

2、开启定时任务

 3、配置定时任务

二 Springboot整合Quartz

1、导入Quartz依赖

 2、编写Job任务

 3、编写Quartz配置文件


 


一 Springboot整合Scheduled

1、导入Scheduled依赖

不需要额外的依赖,只需要导入springboot web依赖即可;

 
<dependency>
 
<groupId>org.springframework.boot</groupId>
 
<artifactId>spring-boot-starter-web</artifactId>
 
</dependency>

 

2、开启定时任务

在项目的启动类上添加 @EnableScheduling注解即可;

 
@SpringBootApplication
 
@EnableScheduling
 
public class SpringbootexampleApplication {
 
 
 
public static void main(String[] args) {
 
SpringApplication.run(SpringbootexampleApplication.class, args);
 
}
 
 
 
}

 

 3、配置定时任务

 
@Component
 
public class MyTask {
 
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
 
 
 
@Scheduled(fixedRate = 5000)
 
public void sendTask(){
 
System.out.println(dateFormat.format(new Date()));
 
}
 
}

 

其中 "fixedRate = 5000"表示在当前任务执行5秒后开启另一个任务;

        "fixedDelay = 5000"表示在当前任务执行结束5秒后开启另一个任务;

        "initialDelay = 5000"表示首次执行的延迟时间;

相关定时任务配置规则可参考:https://www.bejson.com/othertools/cron/

二 Springboot整合Quartz

Quartz的核心要素

任务(Job):我们要执行的某件事情,代码逻辑;

任务详情(JobDetail):描述 Job 的实现类及其他相关的静态信息,以便运行时通过 newInstance() 的反射机制实例化 Job。(不懂,自古牛逼多反射;)

调度器(Scheduler):所有的调度都有它来控制;

触发器(Trigger):决定什么时候来执行任务;

1、导入Quartz依赖

 
<dependency>
 
<groupId>org.springframework.boot</groupId>
 
<artifactId>spring-boot-starter-quartz</artifactId>
 
</dependency>

 

 2、编写Job任务

 
@Component
 
public class MyJob extends QuartzJobBean {
 
 
 
@Override
 
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
 
String msg = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("msg");
 
String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
 
System.out.println(time+"------"+msg);
 
}
 
}

 

 3、编写Quartz配置文件

 
@Configuration
 
public class QuartzConfig {
 
//构建 JobDetail
 
@Bean
 
public JobDetail myJobDetail() {
 
return JobBuilder.newJob(MyJob.class)
 
//给JobDetail起了一个名字;
 
.withIdentity("myJobDetail")
 
//每个JobDetail内部都有一个map,包含了关联到这个Job的数据,在Job类中可以通过context获取;
 
.usingJobData("msg","HelloQuartz")
 
//即使没有Trigger关联时,也不需要删除该JobDetail
 
.storeDurably()
 
.build();
 
}
 
//构建Trigger和Scheduler
 
@Bean
 
public Trigger MyJobTrigger() {
 
return TriggerBuilder.newTrigger()
 
//关联上面的JobDetail;
 
.forJob(myJobDetail())
 
//给Trigger起了一个名字;
 
.withIdentity("MyJobTrigger")
 
//cron 表达式设置每隔 5 秒执行一次
 
.withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ? *"))
 
.build();
 
}
 }

 

posted @ 2020-12-31 12:06  ぁ晴  阅读(61)  评论(0编辑  收藏  举报