springboot中超简单使用quartz添加动态定时任务
1、在springboot2.x中引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
2、使用数据库的需要指定,spring.quartz.job-store-type=jdbc
数据库默认使用spring.datasource.*的配置,
表结构在jar包里面org\quartz-scheduler\quartz\2.3.1\quartz-2.3.1.jar!\org\quartz\impl\jdbcjobstore
3、配置工具类两个方法,一个增加,已删除,其中scheduler已经自动装配,可以直接引用
import org.quartz.*; import org.springframework.stereotype.Component; import javax.annotation.Resource; @Component public class QuartzUtil { @Resource private Scheduler scheduler; /** * 增加一个job * * @param jobDetail * 任务实现类 * @param jobName * 任务名称 * @param jobGroupName * 任务组名 * @param jobTime * 时间表达式 (这是每隔多少秒为一次任务) * @param jobTimes * 运行的次数 (<0:表示不限次数) */ public void addJob( JobDetail jobDetail, String jobName, String jobGroupName, int jobTime, int jobTimes) { try { // 使用simpleTrigger规则 Trigger trigger = null; if (jobTimes < 0) { trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroupName) .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1).withIntervalInSeconds(jobTime)) .startNow().build(); } else { trigger = TriggerBuilder .newTrigger().withIdentity(jobName, jobGroupName).withSchedule(SimpleScheduleBuilder .repeatSecondlyForever(1).withIntervalInSeconds(jobTime).withRepeatCount(jobTimes)) .startNow().build(); } scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 删除任务一个job * * @param jobName * 任务名称 * @param jobGroupName * 任务组名 */ public void deleteJob(String jobName, String jobGroupName) { try { scheduler.deleteJob(new JobKey(jobName, jobGroupName)); } catch (Exception e) { e.printStackTrace(); } } }
4、添加任务类,要继承QuartzJobBean类,这样就能在任务类中注入容器中bean
@Slf4j public class SendEmailJob extends QuartzJobBean { /**
* @Reaource
* private XXXXXXMapper xxxxxMapper
**/ @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { log.info("定时任务"); } }
5、引用
JobDetail jobDetail=JobBuilder.newJob(SendEmailJob.class).build(); quartzUtil.addJob(jobDetail,"","",100,-1);