定时任务 Springboot+quartz+service层不能注入的问题

1 添加依赖

 

   

 <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.0</version>
        </dependency>
View Code

 

2   创建Factory(代码可照抄)

 

 

package com.souche.salt_common_01.config;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

@Component
public class MyJobFactory extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}
View Code

 

3  创建配置文件(代码可照抄)

 

package com.souche.salt_common_01.config;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;


@Configuration
public class QuartzConfig {
    @Autowired
    private MyJobFactory myJobFactory;


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(myJobFactory);
        System.out.println("myJobFactory:"+myJobFactory);
        return schedulerFactoryBean;
    }




    @Bean
    public Scheduler scheduler() {
        return schedulerFactoryBean().getScheduler();
    }


}
View Code

 

4 创建job 定时执行此job里面的方法(你要执行的业务代码在这里面)

package com.souche.salt_common_01.service.impl;

import com.souche.salt_common_01.controller.SctiptsController;
import com.souche.salt_common_01.controller.TimeJobController;
import com.souche.salt_common_01.entity.JobsLog;
import com.souche.salt_common_01.entity.Scripts;
import com.souche.salt_common_01.entity.ScriptsExample;
import com.souche.salt_common_01.mapper.ScriptsMapper;
import com.souche.salt_common_01.service.ClientService;
import com.souche.salt_common_01.utils.IDUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;


public class SchedulerQuartzJob1 implements Job{


    @Autowired
    private TimeJobController timeJobController;




    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {

            System.out.println("开始:"+System.currentTimeMillis());
           //此处可获得你要执行的名字              
        String JobName=arg0.getJobDetail().getKey().getName();
            


        System.out.println("结束:"+System.currentTimeMillis());



    }








}

 

5 创建配置文件(可照抄 )

我只试用过第一个方法startJob 新建一个任务:传入任务名 ,执行时间两个参数,执行时间是cron表达式

 

package com.souche.salt_common_01.config;

import java.util.Date;

import com.souche.salt_common_01.service.impl.SchedulerQuartzJob1;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;


/**
 * 任务调度处理
 * @author yvan
 *
 */
@Configuration
public class QuartzScheduler {
    // 任务调度
    @Autowired
    private Scheduler scheduler;

    /**
     * 开始执行所有任务
     *
     * @throws SchedulerException
     */
    public void startJob(String jobName,String startTime) throws SchedulerException {
        //startJob1(scheduler,name,startTime);
        // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob1.class).withIdentity(jobName, "group1").build();
        // 基于表达式构建触发器
       // CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(startTime);
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, "group1")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
        scheduler.start();
    }

    /**
     * 获取Job信息
     *
     * @param name
     * @param group
     * @return
     * @throws SchedulerException
     */
    public String getJobInfo(String name, String group) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 修改某个任务的执行时间
     *
     * @param name
     * @param group
     * @param time
     * @return
     * @throws SchedulerException
     */
    public void modifyJob(String name, String group, String time) throws SchedulerException {
        Date date = null;
        System.err.println(name);
        System.err.println(group);
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(time)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                    .withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
      //  return date != null?true:false;
    }

    /**
     * 暂停所有任务
     *
     * @throws SchedulerException
     */
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * 暂停某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void pauseJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复所有任务
     *
     * @throws SchedulerException
     */
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * 恢复某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void resumeJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.resumeJob(jobKey);
    }

    /**
     * 删除某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void deleteJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }

 /*   private void startJob1(Scheduler scheduler,String name,String startTime) throws SchedulerException {
        // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob1.class).withIdentity(name, "group1").build();
        // 基于表达式构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
       // CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(startTime);
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name, "group1")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }*/

    private void startJob2(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob2.class).withIdentity("job2", "group2").build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/5 * * * ?");
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job2", "group2")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }
}
View Code

 


6编写API

 

package com.souche.salt_common_01.controller;
import com.souche.salt_common_01.config.QuartzScheduler;
import org.apache.ibatis.annotations.Delete;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/**
 * 这里并没有采用restful风格 只是简单封装了一下api
 *
 * @author yvan
 *
 */
@RestController
public class QuartzApiController {
    @Autowired
    private QuartzScheduler quartzScheduler;

    @PostMapping("/lantu/quartz")
    public void startQuartzJob(String name,String startTime) {

        try {
            quartzScheduler.startJob(name,startTime);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/lantu/info")
    public String getQuartzJob(String name, String group) {
        String info = null;
        try {
            info = quartzScheduler.getJobInfo(name, group);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return info;
    }

    @PutMapping("/lantu/modify")
    public void modifyQuartzJob(String name, String startTime) {

        boolean flag = true;
        try {
             quartzScheduler.modifyJob(name, "group1", startTime);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        //return flag;
    }

    @GetMapping (value = "/lantu/pause")
    public void pauseQuartzJob(String name, String group) {
        try {
            quartzScheduler.pauseJob(name, group);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @GetMapping(value = "/lantu/pauseAll")
    public void pauseAllQuartzJob() {
        try {
            quartzScheduler.pauseAllJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @DeleteMapping(value = "/lantu/delete")
    public void deleteJob(String name, String group) {
        try {
            quartzScheduler.deleteJob(name, group);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

}
View Code

 

 

以上就是完成了一个简单的定时任务:并且解决了SchedulerQuartzJob1中不可以注入其他service 的问题。

但是一但项目重启 这些加入内存的定时任务就会丢失。解决办法如下。

 

7 监听器

对于监听器的使用我并不理解,我只是找了一个解决问题的办法:

每次项目启动的时候 读取数据库中自己存储任务的任务表,把任务重新添加进来。

package com.souche.salt_common_01.config;



import com.souche.salt_common_01.controller.TimeJobController;
import com.souche.salt_common_01.entity.TimeJobs;
import com.souche.salt_common_01.entity.TimeJobsExample;
import com.souche.salt_common_01.mapper.TimeJobsMapper;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.List;

@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent>{
    @Autowired
    private QuartzScheduler quartzScheduler;
    @Autowired
    private TimeJobsMapper timeJobsMapper;


/**
     * 初始启动quartz
     */

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {

            //读取我的数据库  获得要执行的任务名称 和执行时间,然后添加进去
            TimeJobsExample timeJobsExample=new TimeJobsExample();
            timeJobsExample.or().andStatusEqualTo("running");
            List<TimeJobs> timeJobs=timeJobsMapper.selectByExample(timeJobsExample);
            for (TimeJobs tjob:timeJobs
                 ) {
                   quartzScheduler.startJob(tjob.getId(),tjob.getDoTime());
            }


            System.out.println("任务已经启动...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


 

}

 

 

以上只是我工作中暂时解决定时任务的方法:其中我用到了 添加定时任务,和删除定时任务, 其他api有待测试

 

转载于:https://www.cnblogs.com/hhxylm/p/10592872.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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); } } ``` 在这里,我们使用了 QuartzScheduler 接口来动态创建、修改和删除定时任务,并且使用了 @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、付费专栏及课程。

余额充值