SpringBoot2.0+整合Quartz 定时任务

SpringBoot2.X 与定时任务

定时器选择

有基于Quartz的定时器 更全面 有Spring自带的定时 (单线程)基于注解@Scheduled

(1)基于注解@Scheduled

优点:简单,好用,没有复杂场景直接使用他,除了支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可。

缺点:默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响。 可以通过@EnableAsync注解开启多线程

首先在SpringBoot启动类加上一个注解

单线程用法

@EnableScheduling
@Component
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {
    //3.添加定时任务
    @Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔,例如:5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}

多线程用法

@Component     //无实际意义 (交给Spring管理   可不用)
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程 
public class MultithreadScheduleTask {

        @Async  //多线程
        @Scheduled(fixedDelay = 1000)  //间隔1秒
        public void first() throws InterruptedException {
            System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "线程 : " + Thread.currentThread().getName());
            System.out.println();
            Thread.sleep(1000 * 10);
        }

        @Async  //多线程
        @Scheduled(fixedDelay = 2000)
        public void second() {
            System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "线程 : " + Thread.currentThread().getName());
            System.out.println();
        }
    }

(2)Quartz定时器

优点:多线程定时任务 不会因为上一个定时任务未执行完毕而造成定时等待

导包

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

编写任务类 继承 QuartzJobBean 覆写父类 executeInternal方法 ,其中 在executeInternal中编写要定时执行的业务逻辑即可

import cn.leilei.mapper.RealEseateMapper;
import cn.leilei.service.IRealEseateService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component
public class TestQuartz extends QuartzJobBean {

    @Autowired
    private IRealEseateService realEseateService;//测试定时执行  与数据库交互
    /** * 执行定时任务 * * @param jobExecutionContext * @throws JobExecutionException */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        realEseateService.list().forEach(e-> System.out.println(e));
        System.out.println("ttt" + new Date());
    }
}

编写定时任务配置类

两种定时 一种是是触发时间 ,使用cron表达式 ,一直是触发时间 设置触发间隔时间 默认 单位 秒

import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {
    @Bean
    public JobDetail teatQuartzDetail() {
        return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build();
    }

/*    @Bean
    public Trigger testQuartzTrigger() {
        //设置时间周期单位秒 每隔两秒实行一次
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever();
        return TriggerBuilder.newTrigger().forJob(teatQuartzDetail()) .withIdentity("testQuartz") .withSchedule(scheduleBuilder) .build();

    }*/
    //cron 表达式
    @Bean
    public Trigger uploadTaskTrigger() {
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/5 * * * * ?");
        return TriggerBuilder.newTrigger().forJob(teatQuartzDetail())
                .withIdentity("testQuartz")
                .withSchedule(scheduleBuilder)
                .build();
    }
}

至此 ,SpringBoot整合定时任务就完成了,当然这也只是一个简单的整合,没有特别复杂的业务逻辑 已经可以达到了,需要更多的整合可以自行百度 Quartz定时工具类

小提示:

Cron表达式参数分别表示:

  • 秒(0~59) 例如0/5表示每5秒
  • 分(0~59)
  • 时(0~23)
  • 日(0~31)的某天,需计算
  • 月(0~11)
  • 周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,动态定时任务一般需要以下几个步骤: 1. 在后端使用 SpringBootQuartz,定义一个定时任务类,继承自 Quartz 的 Job 接口,并实现其中的 execute 方法。 2. 在定时任务类中,编写需要执行的任务逻辑。 3. 在定时任务类中,添加一些参数,用于动态设置定时任务的执行时间和执行频率。这些参数可以通过注解或者配置文件进行设置。 4. 在前端使用 Vue,创建一个页面,用于展示所有已经添加的定时任务,并且可以动态添加、修改和删除定时任务。 5. 在前端页面中,使用 axios 或者其他 AJAX 库,向后端发送添加、修改和删除定时任务的请求。 6. 后端接收到前端的请求后,根据请求的参数,动态创建、修改或删除 Quartz 定时任务。 具体实现可以参照以下步骤: 1. 在后端使用 SpringBootQuartz,定义一个定时任务类,如下所示: ``` @Component public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 编写需要执行的任务逻辑 } } ``` 2. 在定时任务类中,添加一些参数,用于动态设置定时任务的执行时间和执行频率,如下所示: ``` @Component public class MyJob implements Job { @Value("${job.trigger.cron}") private String cronExpression; @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 编写需要执行的任务逻辑 } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } } ``` 在这里,我们使用了 @Value 注解来从配置文件中读取 cron 表达式,然后通过 setter 方法将其设置到定时任务类中。 3. 在前端使用 Vue,创建一个页面,用于展示所有已经添加的定时任务,并且可以动态添加、修改和删除定时任务。具体实现可以参考以下代码: ``` <template> <div> <h2>定时任务列表</h2> <table> <thead> <tr> <th>ID</th> <th>名称</th> <th>状态</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="job in jobs" :key="job.id"> <td>{{ job.id }}</td> <td>{{ job.name }}</td> <td>{{ job.status }}</td> <td> <button @click="editJob(job)">编辑</button> <button @click="deleteJob(job)">删除</button> </td> </tr> </tbody> </table> <button @click="addJob()">添加定时任务</button> <div v-if="showEditDialog"> <h3>{{ dialogTitle }}</h3> <form> <div> <label>名称:</label> <input type="text" v-model="job.name"> </div> <div> <label>状态:</label> <select v-model="job.status"> <option value="启用">启用</option> <option value="停用">停用</option> </select> </div> <div> <label>执行时间:</label> <input type="text" v-model="job.trigger.cron"> </div> <button @click="saveJob()">保存</button> <button @click="closeDialog()">关闭</button> </form> </div> </div> </template> <script> import axios from 'axios' export default { data() { return { jobs: [], job: { id: null, name: '', status: '启用', trigger: { cron: '' } }, showEditDialog: false, dialogTitle: '' } }, created() { this.getJobs() }, methods: { getJobs() { axios.get('/api/jobs') .then(response => { this.jobs = response.data }) .catch(error => { console.log(error) }) }, addJob() { this.job.id = null this.job.name = '' this.job.status = '启用' this.job.trigger.cron = '' this.dialogTitle = '添加定时任务' this.showEditDialog = true }, editJob(job) { this.job.id = job.id this.job.name = job.name this.job.status = job.status this.job.trigger.cron = job.trigger.cron this.dialogTitle = '编辑定时任务' this.showEditDialog = true }, saveJob() { if (this.job.id == null) { axios.post('/api/jobs', this.job) .then(response => { this.getJobs() this.showEditDialog = false }) .catch(error => { console.log(error) }) } else { axios.put('/api/jobs/' + this.job.id, this.job) .then(response => { this.getJobs() this.showEditDialog = false }) .catch(error => { console.log(error) }) } }, deleteJob(job) { axios.delete('/api/jobs/' + job.id) .then(response => { this.getJobs() }) .catch(error => { console.log(error) }) }, closeDialog() { this.showEditDialog = false } } } </script> ``` 在这里,我们使用了 axios 库来向后端发送 HTTP 请求,并且使用了 v-for 和 v-model 指令来实现页面数据的绑定和循环展示。 4. 在后端使用 SpringBootQuartz,创建一个 RESTful API,用于接收前端页面发送的添加、修改和删除定时任务的请求。具体实现可以参考以下代码: ``` @RestController @RequestMapping("/api/jobs") public class JobController { @Autowired private Scheduler scheduler; @GetMapping("") public List<JobDetail> getAllJobs() throws SchedulerException { List<JobDetail> jobs = new ArrayList<>(); for (String groupName : scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { JobDetail jobDetail = scheduler.getJobDetail(jobKey); jobs.add(jobDetail); } } return jobs; } @PostMapping("") public void addJob(@RequestBody JobDetail jobDetail) throws SchedulerException { JobDataMap jobDataMap = jobDetail.getJobDataMap(); String jobName = jobDataMap.getString("jobName"); String jobGroup = jobDataMap.getString("jobGroup"); String jobClass = jobDataMap.getString("jobClass"); String cronExpression = jobDataMap.getString("cronExpression"); JobDetail newJob = JobBuilder.newJob() .withIdentity(jobName, jobGroup) .ofType((Class<? extends Job>) Class.forName(jobClass)) .build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(jobName + "Trigger", jobGroup) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) .build(); scheduler.scheduleJob(newJob, trigger); } @PutMapping("/{id}") public void updateJob(@PathVariable("id") String id, @RequestBody JobDetail jobDetail) throws SchedulerException { JobDataMap jobDataMap = jobDetail.getJobDataMap(); String jobName = jobDataMap.getString("jobName"); String jobGroup = jobDataMap.getString("jobGroup"); String jobClass = jobDataMap.getString("jobClass"); String cronExpression = jobDataMap.getString("cronExpression"); JobKey jobKey = new JobKey(jobName, jobGroup); JobDetail oldJob = scheduler.getJobDetail(jobKey); JobDetail newJob = JobBuilder.newJob() .withIdentity(jobName, jobGroup) .ofType((Class<? extends Job>) Class.forName(jobClass)) .build(); newJob.getJobDataMap().putAll(oldJob.getJobDataMap()); TriggerKey triggerKey = new TriggerKey(jobName + "Trigger", jobGroup); Trigger oldTrigger = scheduler.getTrigger(triggerKey); Trigger newTrigger = TriggerBuilder.newTrigger() .withIdentity(jobName + "Trigger", jobGroup) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) .build(); scheduler.scheduleJob(newJob, newTrigger); } @DeleteMapping("/{id}") public void deleteJob(@PathVariable("id") String id) throws SchedulerException { String[] ids = id.split(":"); String jobName = ids[0]; String jobGroup = ids[1]; JobKey jobKey = new JobKey(jobName, jobGroup); scheduler.deleteJob(jobKey); } } ``` 在这里,我们使用了 Quartz 的 Scheduler 接口来动态创建、修改和删除定时任务,并且使用了 @RequestBody、@PostMapping、@PutMapping 和 @DeleteMapping 注解来接收前端页面发送的请求。 5. 最后,在 SpringBoot 应用程序的配置文件中,添加 Quartz 的相关配置,如下所示: ``` quartz: job-store-type: memory properties: org: quartz: scheduler: instanceName: myScheduler instanceId: AUTO jobFactory: class: org.springframework.scheduling.quartz.SpringBeanJobFactory jobStore: class: org.quartz.simpl.RAMJobStore threadPool: class: org.quartz.simpl.SimpleThreadPool threadCount: 10 threadPriority: 5 threadsInheritContextClassLoaderOfInitializingThread: true ``` 在这里,我们设置了 Quartz 的存储类型为内存存储,以及一些基本的配置项,如线程池大小和线程优先级等。 以上就是动态定时任务的实现步骤,希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值