quartz定时任务spring boot
时间: 2023-05-13 14:02:42 浏览: 173
Quartz是一种广泛使用的开源任务调度框架,可以轻松地在Java应用程序中实现定期执行任务或计划任务。它提供了很多强大的功能,如支持分布式调度、可靠的执行触发器、动态添加/删除触发器、任务持久化等。
Spring Boot是一款强大的开源框架,能够基于Spring和Spring MVC快速构建Web应用程序,而且能够轻松集成其他开源框架,包括Quartz。
Quartz和Spring Boot的结合使用,可以实现更加高效和可靠的定时任务,同时也能够简化任务的创建和管理。要使用Quartz和Spring Boot,需要在POM文件中添加Quartz和Spring Boot的依赖,然后创建一个带有@Scheduled注释的任务类。
在添加了依赖之后,在配置文件中配置Quartz Scheduler Factory Bean以及Job Detail Bean,用于创建具体的任务。然后通过触发器对象来定义任务运行的时间表,包括任务开始时间、结束时间和频率等等。
最后,在Spring Boot应用程序启动时,Quartz会自动启动并定期执行任务。通过Quartz和Spring Boot的结合,开发者能够轻松实现各种类型的定时任务,并且能够迅速测试和调试任务,以保证系统的稳定性和有效性。
相关问题
使用Quartz2.3.2+spring boot实现数据库持久化存储多个定时任务
好的,我了解了你的问题。要使用Quartz2.3.2和Spring Boot实现数据库持久化存储多个定时任务,你可以按照以下步骤操作:
1. 在Spring Boot项目中添加Quartz2.3.2的依赖包:
```xml
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
```
2. 创建一个继承了`org.quartz.impl.jdbcjobstore.PostgreSQLDelegate`的类,用于实现PostgreSQL数据库的存储。
```java
public class PostgreSQLDelegateCustom extends PostgreSQLDelegate {
private String tablePrefix = "";
public PostgreSQLDelegateCustom() {
super();
}
@Override
public void setInstanceName(String schedName) {
super.setInstanceName(schedName);
this.tablePrefix = schedName + ".";
}
@Override
public String getSelectNextTriggerToAcquireSql(int maxCount) {
return "SELECT * FROM " + tablePrefix + "QRTZ_TRIGGERS WHERE " + "TRIGGER_STATE = ? AND NEXT_FIRE_TIME <= ? " + "AND MISFIRE_INSTR IN (" + MisfireInstruction.IGNORE_MISFIRE_POLICY + "," + MisfireInstruction.SMART_POLICY + ") ORDER BY NEXT_FIRE_TIME ASC";
}
@Override
public String getSelectNextMisfiredTriggersInStateSql(Connection conn, String state, long ts) {
return "SELECT * FROM " + tablePrefix + "QRTZ_TRIGGERS WHERE " + "TRIGGER_STATE = ? AND NEXT_FIRE_TIME <= ? " + "AND MISFIRE_INSTR NOT IN (" + MisfireInstruction.IGNORE_MISFIRE_POLICY + "," + MisfireInstruction.SMART_POLICY + ") ORDER BY NEXT_FIRE_TIME ASC";
}
@Override
public String getSelectPausedTriggerGroupsSql() {
return "SELECT TRIGGER_GROUP FROM " + tablePrefix + "QRTZ_PAUSED_TRIGGER_GRPS";
}
@Override
public String getSelectPausedTriggerGroupsLikeSql() {
return "SELECT TRIGGER_GROUP FROM " + tablePrefix + "QRTZ_PAUSED_TRIGGER_GRPS WHERE TRIGGER_GROUP LIKE ?";
}
@Override
public String getSelectFiredTriggersSql(int limit) {
return "SELECT * FROM " + tablePrefix + "QRTZ_FIRED_TRIGGERS ORDER BY FIRE_TIME ASC LIMIT " + limit;
}
@Override
public String getSelectFiredTriggerSql() {
return "SELECT * FROM " + tablePrefix + "QRTZ_FIRED_TRIGGERS WHERE ENTRY_ID = ?";
}
@Override
public String getInsertPausedTriggerGroupSql() {
return "INSERT INTO " + tablePrefix + "QRTZ_PAUSED_TRIGGER_GRPS (TRIGGER_GROUP) VALUES (?)";
}
@Override
public String getDeletePausedTriggerGroupSql() {
return "DELETE FROM " + tablePrefix + "QRTZ_PAUSED_TRIGGER_GRPS WHERE TRIGGER_GROUP = ?";
}
@Override
public String getDeleteAllPausedTriggerGroupsSql() {
return "DELETE FROM " + tablePrefix + "QRTZ_PAUSED_TRIGGER_GRPS";
}
@Override
public String getInsertFiredTriggerSql() {
return "INSERT INTO " + tablePrefix + "QRTZ_FIRED_TRIGGERS (ENTRY_ID, " + "TRIGGER_NAME, TRIGGER_GROUP, " + "IS_VOLATILE, INSTANCE_NAME, " + "FIRED_TIME, SCHED_TIME, " + "PRIORITY, STATE, JOB_NAME, " + "JOB_GROUP, IS_STATEFUL, " + "REQUESTS_RECOVERY, " + "MISFIRE_INSTR) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
}
@Override
public String getUpdateFiredTriggerSql() {
return "UPDATE " + tablePrefix + "QRTZ_FIRED_TRIGGERS SET " + "FIRED_TIME = ?, SCHED_TIME = ?, STATE = ? " + "WHERE ENTRY_ID = ?";
}
@Override
public String getDeleteFiredTriggerSql() {
return "DELETE FROM " + tablePrefix + "QRTZ_FIRED_TRIGGERS WHERE ENTRY_ID = ?";
}
@Override
public String getDeleteFiredTriggersSql(String instanceId) {
return "DELETE FROM " + tablePrefix + "QRTZ_FIRED_TRIGGERS WHERE INSTANCE_NAME = ?";
}
@Override
public String getSelectInstancesFiredTriggerCountSql() {
return "SELECT COUNT(*) FROM " + tablePrefix + "QRTZ_FIRED_TRIGGERS WHERE INSTANCE_NAME = ?";
}
}
```
3. 在Spring Boot配置文件中配置Quartz的相关参数:
```yaml
spring:
quartz:
job-store-type: jdbc
properties:
org:
quartz:
scheduler:
instanceId: AUTO
instanceName: my-scheduler
jobStore:
driverDelegateClass: com.example.PostgreSQLDelegateCustom
useProperties: false
isClustered: false
dataSource: myDataSource
tablePrefix: QRTZ_
threadPool:
threadCount: 10
plugin:
shutdownhook:
class: org.quartz.plugins.management.ShutdownHookPlugin
cleanShutdown: true
jobHistory:
class: org.quartz.plugins.history.LoggingJobHistoryPlugin
jobHistoryLogLevel: INFO
```
4. 创建一个继承了`org.quartz.Job`的类,用于定义任务的具体逻辑:
```java
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 任务逻辑代码
}
}
```
5. 在Spring Boot的任意一个类中添加以下代码,用于配置和启动Quartz Scheduler:
```java
@Configuration
public class QuartzConfig {
@Bean
public JobDetail myJobDetail() {
return JobBuilder.newJob(MyJob.class)
.withIdentity("myJob")
.storeDurably()
.build();
}
@Bean
public Trigger myTrigger() {
return TriggerBuilder.newTrigger()
.forJob(myJobDetail())
.withIdentity("myTrigger")
.withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
.build();
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setDataSource(dataSource);
schedulerFactoryBean.setJobDetails(myJobDetail());
schedulerFactoryBean.setTriggers(myTrigger());
return schedulerFactoryBean;
}
}
```
6. 最后,你需要在PostgreSQL数据库中创建Quartz所需的表结构。你可以使用Quartz提供的`tables_postgres.sql`文件进行创建。
至此,你已经成功实现了使用Quartz2.3.2和Spring Boot实现数据库持久化存储多个定时任务。
spring boot+quartz实现定时任务管理
使用Spring Boot和Quartz实现定时任务管理,可以让你更方便地管理和监控你的定时任务。下面是一个使用Spring Boot、Quartz和Spring MVC实现定时任务管理的示例:
首先,在你的Spring Boot应用程序中添加Quartz和Spring MVC的依赖项:
```xml
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
然后,在你的Spring Boot应用程序中创建一个Quartz的调度器,并添加一个Spring MVC的Controller来管理定时任务:
```java
@Configuration
public class QuartzConfig {
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setTriggers(myTaskTrigger().getObject());
return schedulerFactoryBean;
}
@Bean
public JobDetailFactoryBean myTaskJob() {
JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
jobDetailFactoryBean.setJobClass(MyTask.class);
return jobDetailFactoryBean;
}
@Bean
public CronTriggerFactoryBean myTaskTrigger() {
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setJobDetail(myTaskJob().getObject());
cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?"); // 每5秒执行一次
return cronTriggerFactoryBean;
}
}
@RestController
public class TaskController {
@Autowired
private Scheduler scheduler;
@PostMapping("/tasks")
public void addTask(@RequestBody TaskInfo taskInfo) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(taskInfo.getJobClass())
.withIdentity(taskInfo.getJobName(), taskInfo.getJobGroup())
.build();
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(taskInfo.getTriggerName(), taskInfo.getTriggerGroup())
.withSchedule(CronScheduleBuilder.cronSchedule(taskInfo.getCronExpression()))
.build();
scheduler.scheduleJob(jobDetail, trigger);
}
@DeleteMapping("/tasks/{jobName}/{jobGroup}")
public void deleteTask(@PathVariable String jobName, @PathVariable String jobGroup) throws SchedulerException {
JobKey jobKey = new JobKey(jobName, jobGroup);
scheduler.deleteJob(jobKey);
}
}
```
在上面的代码中,我们创建了一个Spring MVC的Controller来管理定时任务。我们使用了Scheduler类来添加和删除定时任务。在添加定时任务时,我们使用了TaskInfo类来封装定时任务的信息。在删除定时任务时,我们使用了jobName和jobGroup来识别定时任务。
最后,在你的定时任务类中实现Job接口,并在类上添加@DisallowConcurrentExecution注解,以确保每个任务执行时只有一个实例:
```java
@Component
@DisallowConcurrentExecution
public class MyTask implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 定时任务执行的代码
}
}
```
以上就是使用Spring Boot、Quartz和Spring MVC实现定时任务管理的示例。
阅读全文