spring boot整合quartz存储到数据库

首先是pom.xml依赖 1 <!--quartz依赖--> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifac...

首先是pom.xml依赖

1 <!--quartz依赖-->
2         <dependency>
3             <groupId>org.springframework.boot</groupId>
4             <artifactId>spring-boot-starter-quartz</artifactId>
5         </dependency>
pom.xml

就一个controller就可以,剩下的自己去写存储数据库的方法

  1 package com.family.Switch.controller;
  2 
  3 import java.text.SimpleDateFormat;
  4 import java.util.Date;
  5 import java.util.List;
  6 import java.util.concurrent.TimeUnit;
  7 
  8 import org.jboss.logging.Logger;
  9 import org.quartz.CronScheduleBuilder;
 10 import org.quartz.CronTrigger;
 11 import org.quartz.Job;
 12 import org.quartz.JobBuilder;
 13 import org.quartz.JobDetail;
 14 import org.quartz.JobExecutionContext;
 15 import org.quartz.JobExecutionException;
 16 import org.quartz.JobKey;
 17 import org.quartz.Scheduler;
 18 import org.quartz.SchedulerException;
 19 import org.quartz.Trigger;
 20 import org.quartz.TriggerBuilder;
 21 import org.quartz.TriggerKey;
 22 import org.springframework.beans.factory.annotation.Autowired;
 23 //import org.springframework.scheduling.Trigger;
 24 import org.springframework.stereotype.Component;
 25 import org.springframework.web.bind.annotation.RequestMapping;
 26 import org.springframework.web.bind.annotation.RequestMethod;
 27 import org.springframework.web.bind.annotation.RequestParam;
 28 import org.springframework.web.bind.annotation.ResponseBody;
 29 import org.springframework.web.bind.annotation.RestController;
 30 
 31 import com.family.Switch.job.CrawlNewsJob;
 32 import com.family.Switch.model.ScheduledTask;
 33 import com.family.Switch.service.IScheduledTaskService;
 34 import com.family.util.mqtt.ServerMQTT;
 35 
 36 import io.swagger.annotations.Api;
 37 import io.swagger.annotations.ApiImplicitParam;
 38 import io.swagger.annotations.ApiImplicitParams;
 39 import io.swagger.annotations.ApiOperation;
 40  
 41 
 42 @Component
 43 @Api(value = "手动定时开关",description ="手动定时开关")
 44 @RestController
 45 @RequestMapping(value = "/trigger")
 46 public class DynamicTaskController implements Job {
 47 
 48     @Autowired
 49     private ServerMQTT servermqtt;
 50     
 51     @Autowired
 52     private IScheduledTaskService ischeduledtaskservice;
 53     
 54     @Autowired
 55     private Scheduler scheduler;
 56     
 57     public final Logger log = Logger.getLogger(this.getClass());
 58     
 59     //全局变量
 60     //private String cronStr = "0/5 * * * * ?";
 61  
 62     @ApiOperation(value="添加定时", notes="添加定时")
 63     @RequestMapping(value = "/startCronadd", method = RequestMethod.POST)
 64     @ApiImplicitParams({
 65         @ApiImplicitParam(name="cronStr",value="corn值",dataType="string", paramType = "query"),
 66         @ApiImplicitParam(name="news",value="传给传感器的参数控制开关",dataType="string", paramType = "query"),
 67         @ApiImplicitParam(name="logger",value="log",dataType="string", paramType = "query"),
 68         @ApiImplicitParam(name="key",value="唯一的",dataType="string", paramType = "query"),
 69         @ApiImplicitParam(name="group",value="唯一的",dataType="string", paramType = "query")
 70         })
 71     @ResponseBody
 72     public String addcon(@RequestParam("cronStr") String cronStr,@RequestParam("news") String news,@RequestParam("logger") String logger,@RequestParam("key") String key,@RequestParam("group") String group) {
 73         
 74         
 75         try {
 76             //Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
 77 //            scheduler.start();
 78             // 启动
 79             if (!scheduler.isShutdown()) {
 80                 
 81                 ScheduledTask scheduledtask=new ScheduledTask();
 82                 
 83                 SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 84                 
 85                 scheduledtask.setCreateTime(df.format(new Date()));
 86                 
 87                 scheduledtask.setTaskKey(key);
 88                 
 89                 scheduledtask.setTaskDesc(group);
 90                 
 91                 scheduledtask.setTaskCron(cronStr);
 92                 
 93                 scheduledtask.setInitStartFlag(1);
 94                 
 95                 int selectcount = ischeduledtaskservice.selectcount(scheduledtask);
 96                 
 97                 if (selectcount>0) {
 98                     log.info("已有数据");
 99                 }else {
100                         scheduler.start();
101                         System.out.println("Quartz Start !");
102                         //具体任务
103                         JobDetail job = JobBuilder.newJob(DynamicTaskController.class).withIdentity(key,group).build();
104 
105                         //触发器
106                        // SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInMinutes(60).repeatForever();
107                         Trigger trigger = TriggerBuilder.newTrigger().withIdentity(key,group).startNow().withSchedule(CronScheduleBuilder.cronSchedule(cronStr)).build();
108 
109                         scheduler.scheduleJob(job,trigger);
110                     
111                     
112                     ischeduledtaskservice.insert(scheduledtask);
113                     log.info("添加完毕");
114                 }
115                 
116             }
117             //睡眠
118             TimeUnit.MINUTES.sleep(1);
119             scheduler.shutdown(true);
120             
121             if(scheduler.isShutdown()) {
122                   ScheduledTask scheduledtask=new ScheduledTask();
123                   SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
124                   scheduledtask.setUpdateTime(df.format(new Date()));
125                   scheduledtask.setInitStartFlag(0);
126                   scheduledtask.setTaskCron(cronStr);
127                 int update = ischeduledtaskservice.update(scheduledtask);
128                 if (update>0) {
129                     log.info("状态修改完成");
130                 }
131             }
132             System.out.println("scheduler shutdown ! ");
133         }catch(Exception e){
134             e.printStackTrace();
135       }
136         
137         
138 //        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new Trigger(){
139 //
140 //
141 //            @Override
142 //            public Date nextExecutionTime(TriggerContext triggerContext) {
143 //                try {
144 //                    servermqtt.mqtt(news, "test");
145 //                } catch (MqttException e) {
146 //                    // TODO Auto-generated catch block
147 //                    e.printStackTrace();
148 //                }
149 //                return new CronTrigger(cronStr).nextExecutionTime(triggerContext);
150 //            }
151 //
152 //    });
153         
154         return "startCronadd";
155     }
156     
157     
158     @ApiOperation(value="查询所有定时任务", notes="查询所有定时任务")
159     @RequestMapping(value = "/stopCronselect", method = RequestMethod.GET)
160     public List stopCronselect() {
161        return ischeduledtaskservice.select();
162     }
163     
164     @ApiOperation(value="更新定时", notes="更新定时")
165     @RequestMapping(value = "/updatecron", method = RequestMethod.POST)
166     @ApiImplicitParams({
167         @ApiImplicitParam(name="cronStr",value="corn值",dataType="string", paramType = "query"),
168         @ApiImplicitParam(name="key",value="log",dataType="string", paramType = "query"),
169         @ApiImplicitParam(name="group",value="log",dataType="string", paramType = "query")
170         })
171     @ResponseBody
172     public String updatecron(@RequestParam("cronStr") String cronStr,@RequestParam("key") String key,@RequestParam("group") String group) throws SchedulerException {
173         
174          TriggerKey triggerKey = TriggerKey.triggerKey(key, group);
175          
176          CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
177   
178          CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronStr);
179   
180          trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
181   
182          scheduler.rescheduleJob(triggerKey, trigger);
183          
184          ScheduledTask scheduledtask=new ScheduledTask();
185              SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
186              scheduledtask.setUpdateTime(df.format(new Date()));
187              scheduledtask.setInitStartFlag(1);
188              scheduledtask.setTaskCron(cronStr);
189            int update = ischeduledtaskservice.update(scheduledtask);
190            if (update>0) {
191                 log.info("状态修改完成");
192             }
193         
194         return "updatecron";
195     }
196     
197     
198 
199 //    @RequestMapping("/startCron")
200 //    public String startCron() {
201 //
202 //       future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("0/5 * * * * ?"));
203 //        
204 //       System.out.println("DynamicTask.startCron()");
205 //
206 //       return "startCron";
207 //
208 //    }
209     
210     @ApiOperation(value="删除定时", notes="删除定时")
211     @RequestMapping(value = "/deletestopCron", method = RequestMethod.POST)
212     @ApiImplicitParams({
213         @ApiImplicitParam(name="key",value="log",dataType="string", paramType = "query"),
214         @ApiImplicitParam(name="group",value="log",dataType="string", paramType = "query")
215         })
216     @ResponseBody
217     public String deletestopCron(@RequestParam("key") String key,@RequestParam("group") String group) throws SchedulerException {
218         JobKey jobKey = JobKey.jobKey(key,group);
219         scheduler.deleteJob(jobKey);
220         ScheduledTask scheduledtask=new ScheduledTask();
221         scheduledtask.setTaskKey(key);
222         int delete = ischeduledtaskservice.delete(scheduledtask);
223         if(scheduler.isShutdown() && delete>0) {
224             log.info("已关闭");
225         }
226         
227        return "deletestopCron";
228     }
229 
230 
231         @Override
232         public void execute(JobExecutionContext context) throws JobExecutionException {
233             System.out.println("111111111111111111111");
234         }
235 
236  
237 
238 //    @ApiOperation(value="停止", notes="停止")
239 //    @RequestMapping(value = "/stopCron", method = RequestMethod.GET)
240 //    public String stopCron() {
241 //       if (future != null) {
242 //           future.cancel(true);
243 //       }
244 //       System.out.println("DynamicTask.stopCron()");
245 //       return "stopCron";
246 //    }
247 
248  
249 
250 //    @RequestMapping("/changeCron10")
251 //
252 //    public String startCron10() {
253 //
254 //       stopCron();// 先停止,在开启.
255 //
256 //       future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("0/2 * * * * ?"));
257 //
258 //       System.out.println("DynamicTask.startCron10()");
259 //
260 //       return "changeCron10";
261 //
262 //    }
263     
264     
265 
266 //    private class MyRunnable implements Runnable {
267 //
268 //       @Override
269 //
270 //       public void run() {
271 //
272 //           System.out.println("DynamicTask.MyRunnable.run()," + new Date());
273 //
274 //       }
275 //
276 //    }
277 
278  
279 
280 }

最后附赠一个关于开启,关闭,添加,恢复可自行添加到自己的代码里面,这个下面的用不到只用到其中看那些方法能用就自己的方法里面就可以

  1 package com.xlt.xfzb.util;
  2  
  3  
  4 import com.xlt.xfzb.entity.Dingshi;
  5 import org.apache.log4j.Logger;
  6 import org.quartz.*;
  7 import org.quartz.DateBuilder.IntervalUnit;
  8 import org.quartz.impl.matchers.GroupMatcher;
  9 import org.springframework.beans.factory.annotation.Autowired;
 10 import org.springframework.stereotype.Service;
 11  
 12  
 13 import java.util.ArrayList;
 14 import java.util.List;
 15 import java.util.Set;
 16 /**
 17  * @Classname QuartzManager
 18  * @Description TODO
 19  * @Date 2019/12/2 11:04
 20  * @Created by xm
 21  */
 22 @Service
 23 public class QuartzManager {
 24  
 25     public final Logger log = Logger.getLogger(this.getClass());
 26     @Autowired
 27     private Scheduler scheduler;
 28  
 29     /**
 30      * 添加任务
 31      *
 32      * @param
 33      * @throws SchedulerException
 34      */
 35     @SuppressWarnings("unchecked")
 36     public void addJob(Dingshi task) {
 37         try {
 38             // 创建jobDetail实例,绑定Job实现类
 39             // 指明job的名称,所在组的名称,以及绑定job类
 40  
 41             Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(task.getBean_name()).newInstance()
 42                     .getClass());
 43             JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(task.getJob_name(), task.getJobGroup())// 任务名称和组构成任务key
 44                     .build();
 45             // 定义调度触发规则
 46             // 使用cornTrigger规则
 47             Trigger trigger = TriggerBuilder.newTrigger().withIdentity(task.getJob_name(), task.getJobGroup())// 触发器key
 48                     .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
 49                     .withSchedule(CronScheduleBuilder.cronSchedule(task.getCron())).startNow().build();
 50             // 把作业和触发器注册到任务调度中
 51             scheduler.scheduleJob(jobDetail, trigger);
 52             // 启动
 53             if (!scheduler.isShutdown()) {
 54                 scheduler.start();
 55             }
 56         } catch (Exception e) {
 57             e.printStackTrace();
 58         }
 59     }
 60  
 61     /**
 62      * 获取所有计划中的任务列表
 63      *
 64      * @return
 65      * @throws SchedulerException
 66      */
 67     public List<Dingshi> getAllJob() throws SchedulerException {
 68         GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
 69         Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
 70         List<Dingshi> jobList = new ArrayList<Dingshi>();
 71         for (JobKey jobKey : jobKeys) {
 72             List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
 73             for (Trigger trigger : triggers) {
 74                 Dingshi job = new Dingshi();
 75                 job.setJob_name(jobKey.getName());
 76                 job.setJobGroup(jobKey.getGroup());
 77                 job.setRemark("触发器:" + trigger.getKey());
 78                 Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
 79                 job.setStatus(triggerState.name());
 80                 if (trigger instanceof CronTrigger) {
 81                     CronTrigger cronTrigger = (CronTrigger) trigger;
 82                     String cronExpression = cronTrigger.getCronExpression();
 83                     job.setCron(cronExpression);
 84                 }
 85                 jobList.add(job);
 86             }
 87         }
 88         return jobList;
 89     }
 90  
 91     /**
 92      * 所有正在运行的job
 93      *
 94      * @return
 95      * @throws SchedulerException
 96      */
 97     public List<Dingshi> getRunningJob() throws SchedulerException {
 98         List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
 99         List<Dingshi> jobList = new ArrayList<Dingshi>(executingJobs.size());
100         for (JobExecutionContext executingJob : executingJobs) {
101             Dingshi job = new Dingshi();
102             JobDetail jobDetail = executingJob.getJobDetail();
103             JobKey jobKey = jobDetail.getKey();
104             Trigger trigger = executingJob.getTrigger();
105             job.setJob_name(jobKey.getName());
106             job.setJobGroup(jobKey.getGroup());
107             job.setRemark("触发器:" + trigger.getKey());
108             Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
109             job.setStatus(triggerState.name());
110             if (trigger instanceof CronTrigger) {
111                 CronTrigger cronTrigger = (CronTrigger) trigger;
112                 String cronExpression = cronTrigger.getCronExpression();
113                 job.setCron(cronExpression);
114             }
115             jobList.add(job);
116         }
117         return jobList;
118     }
119  
120     /**
121      * 暂停一个job
122      *
123      * @param dingshi
124      * @throws SchedulerException
125      */
126     public void pauseJob(Dingshi dingshi) throws SchedulerException {
127         JobKey jobKey = JobKey.jobKey(dingshi.getJob_name(), dingshi.getJobGroup());
128         scheduler.pauseJob(jobKey);
129     }
130  
131     /**
132      * 恢复一个job
133      *
134      * @param task
135      * @throws SchedulerException
136      */
137     public void resumeJob(Dingshi task) throws SchedulerException {
138         JobKey jobKey = JobKey.jobKey(task.getJob_name(), task.getJobGroup());
139         scheduler.resumeJob(jobKey);
140     }
141  
142     /**
143      * 删除一个job
144      *
145      * @param task
146      * @throws SchedulerException
147      */
148     public void deleteJob(Dingshi task) throws SchedulerException {
149         JobKey jobKey = JobKey.jobKey(task.getJob_name(), task.getJobGroup());
150         scheduler.deleteJob(jobKey);
151  
152     }
153  
154     /**
155      * 立即执行job
156      *
157      * @param task
158      * @throws SchedulerException
159      */
160     public void runJobNow(Dingshi task) throws SchedulerException {
161         JobKey jobKey = JobKey.jobKey(task.getJob_name(), task.getJobGroup());
162         scheduler.triggerJob(jobKey);
163     }
164  
165     /**
166      * 更新job时间表达式
167      *
168      * @param task
169      * @throws SchedulerException
170      */
171     public void updateJobCron(Dingshi task) throws SchedulerException {
172  
173         TriggerKey triggerKey = TriggerKey.triggerKey(task.getJob_name(), task.getJobGroup());
174  
175         CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
176  
177         CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCron());
178  
179         trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
180  
181         scheduler.rescheduleJob(triggerKey, trigger);
182     }
183 }
  • 发表于 2020-05-27 13:59
  • 阅读 ( 175 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除