使用springboot+quartz,项目启动后立即触发执行任务,给出代码
时间: 2024-03-24 10:37:05 浏览: 77
基于springboot和quartz的集中式任务调度系统
3星 · 编辑精心推荐
好的,以下是使用springboot+quartz,项目启动后立即触发执行任务的代码示例:
1. 在pom.xml中添加quartz的依赖
```xml
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
```
2. 在application.yml中配置quartz的相关信息
```yml
spring:
quartz:
job-store-type: MEMORY
properties:
org:
quartz:
scheduler:
instanceName: MyScheduler
instanceId: AUTO
jobStore:
class: org.quartz.simpl.RAMJobStore
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 5
threadPriority: 5
```
3. 创建一个Job类,用于执行定时任务
```java
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Hello, Quartz!");
}
}
```
4. 创建一个Trigger类,用于触发定时任务
```java
public class MyTrigger {
public static Trigger createTrigger() {
return TriggerBuilder.newTrigger()
.withIdentity("MyTrigger", "MyGroup")
.startNow()
.build();
}
}
```
5. 创建一个Scheduler类,用于调度定时任务
```java
@Configuration
public class QuartzConfig {
@Autowired
private ApplicationContext applicationContext;
@Bean
public JobDetail myJobDetail() {
return JobBuilder.newJob(MyJob.class)
.withIdentity("MyJob", "MyGroup")
.storeDurably(true)
.build();
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setApplicationContextSchedulerContextKey("applicationContext");
factory.setConfigLocation(new ClassPathResource("quartz.properties"));
factory.setJobFactory(springBeanJobFactory());
return factory;
}
@Bean
public SpringBeanJobFactory springBeanJobFactory() {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean
public Scheduler scheduler() throws IOException {
Scheduler scheduler = schedulerFactoryBean().getScheduler();
scheduler.setJobFactory(springBeanJobFactory());
scheduler.scheduleJob(myJobDetail(), MyTrigger.createTrigger());
scheduler.start();
return scheduler;
}
}
```
6. 最后,启动springboot应用程序,即可观察到控制台输出"Hello, Quartz!",表示定时任务已经被执行。
注意:在上述代码中,我们使用了SpringBeanJobFactory类,它可以将Job类中通过@Autowired注入的Spring组件自动注入到Job类中。如果您的Job类没有依赖Spring组件,则无需使用该类。
阅读全文