springMVC的定时器
大家好,本人从事软件行业已有8年,大部分时间从事软件开发编写工作。好了废话少说了哈哈哈,直接干货。
在Java开发过程中有很多业务需求里面需要我们实时处理一些动态的业务比如库存的数据动态更新,实时数据的采集等。
遇到这些问题平常的思维和解决方法可能没有那么高效的进行处理,笨办法写个死循环处理你的业务,首先这样对你服务器CPU的负载是个考验,所以不能这样干。。
1.Java本身的Timer方法是解决的途径
new Timer().schedule(new TimerTask(){
@Override
public void run (){
System.out.println("定时任务bombing");
}
},10) //间隔多长时间
这个方法大部分程序猿应该都会,并快速处理你的业务,但这种方法太过于死板,没办法灵活的处理更复杂的定时任务需求,随着你的业务系统的增多,对业务需求量的增大
你的老板可能还是希望你用一个动态的创建定时任务的代码咯,对吧,毕竟我们有成熟的解决方案,以下的这种方法就能轻松的解决你的业务需求。以下是基于SpringMVC的框架加quartz来解决
1.首先下载你的quartz的JAR包

将下载的包放进你的lib里面
2.spring 配置文件添加以下配置
在配置文件表头里面添加
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd"
配置文件里面添加以下
<!-- task任务扫描注解 定时任务-->
<mvc:annotation-driven/>
<context:component-scan base-package="task" />
<!-- 开启这个配置 spring才能识别@Scheduled注解 定时任务-->
<task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
<task:scheduler id="qbScheduler" pool-size="10"/>
3.在web.xml里面进行配置
<!--定时器-->
<!--需要spring这个依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!-- Quartz依赖 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.2</version>
</dependency>
4.在你的目录里面创建task目录
5.在task目录底下创建task.java类
package task;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.CronScheduleBuilder.*;
public class Task {
private static String JOB_GROUP_NAME = "JOB_GROUP_SYSTEM";
private static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_SYSTEM";
public static void addJob(Scheduler sched, String jobName, @SuppressWarnings("rawtypes") Class cls, String time) {
try {
JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
@SuppressWarnings("unchecked")
JobDetail jobDetail = newJob(cls).withIdentity(jobKey).build();
TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
Trigger trigger = newTrigger().withIdentity(triggerKey).withSchedule(cronSchedule(time)).build();
sched.scheduleJob(jobDetail, trigger);
if (!sched.isShutdown()) {
sched.start();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void addJob(Scheduler sched, String jobName, String jobGroupName, String triggerName,
String triggerGroupName, @SuppressWarnings("rawtypes") Class jobClass, String time) {
try {
JobKey jobKey = new JobKey(jobName, jobGroupName);
@SuppressWarnings("unchecked")
JobDetail jobDetail = newJob(jobClass).withIdentity(jobKey).build();
TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
Trigger trigger = newTrigger().withIdentity(triggerKey).withSchedule(cronSchedule(time)).build();
sched.scheduleJob(jobDetail, trigger);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("rawtypes")
public static void modifyJobTime(Scheduler sched, String jobName, String time) {
try {
TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
if (trigger == null) {
return;
}
String oldTime = trigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(time)) {
JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
JobDetail jobDetail = sched.getJobDetail(jobKey);
Class objJobClass = jobDetail.getJobClass();
removeJob(sched, jobName);
System.out.println("输出工作" + jobName);
addJob(sched, jobName, objJobClass, time);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void modifyJobTime(Scheduler sched, String triggerName, String triggerGroupName, String time) {
try {
TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
if (trigger == null) {
return;
}
String oldTime = trigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(time)) {
trigger.getTriggerBuilder().withSchedule(cronSchedule(time));
sched.resumeTrigger(triggerKey);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void removeJob(Scheduler sched, String jobName) {
try {
TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
sched.pauseTrigger(triggerKey);
sched.unscheduleJob(triggerKey);
JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
sched.deleteJob(jobKey);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void removeJob(Scheduler sched, String jobName, String jobGroupName, String triggerName,
String triggerGroupName) {
try {
TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
sched.pauseTrigger(triggerKey);
sched.unscheduleJob(triggerKey);
JobKey jobKey = new JobKey(jobName, jobGroupName);
sched.deleteJob(jobKey);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void startJobs(Scheduler sched) {
try {
sched.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void shutdownJobs(Scheduler sched) {
try {
if (!sched.isShutdown()) {
sched.shutdown();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
以上是核心工具类对定时任务业务处理
6.在创建task的操作类IndexData
package task;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.Data;
import bean.Log;
import bean.Wind;
import dao.DataDao;
import dao.LogDao;
import dao.WindDao;
public class IndexData implements Job{
private static Logger log = LoggerFactory.getLogger(IndexData.class);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
importCsv();//此处写你业务处理逻辑
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("---开启测试定时任务----");
}
}
7.所有流程已经就绪开始你的动态定时任务管理的操作在controller目录里面写你的业务 job.java
package controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import bean.Crons;
import dao.DataDao;
import dao.JobDao;
import task.Task;
@Controller
public class Job {
@Autowired
private StdSchedulerFactory s;
@RequestMapping("/start")
public String add(String jobid) throws ClassNotFoundException, SchedulerException {
Scheduler sche = s.getScheduler();
String result = "";
long times = System.currentTimeMillis();
String t = String.valueOf(times/1000);
HttpSession s = getSession();
if(s.getAttribute("userid")==null){result = "redirect:/adminlogin";}else{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JobDao dao = (JobDao)context.getBean("jobdao");
List<Crons> jobs= dao.queryByjobId(Integer.valueOf(jobid));//动态查询表的一条定时任务
if(!jobs.isEmpty()){
if(!isStart(jobs.get(0).getJobName()))
{
Task.addJob(sche, jobs.get(0).getJobName(), Class.forName(jobs.get(0).getTargetClassName()), jobs.get(0).getCronExpression());
dao.updateJobStatus(Integer.valueOf(jobid), 1);
result = "redirect:/jobAll";
System.out.println("任务开启:"+jobs.get(0).getJobName());
}else {
Task.removeJob(sche, jobs.get(0).getJobName());
System.out.println("任务关闭:"+jobs.get(0).getJobName());
Task.addJob(sche, jobs.get(0).getJobName(), Class.forName(jobs.get(0).getTargetClassName()), jobs.get(0).getCronExpression());
System.out.println("任务开启:"+jobs.get(0).getJobName());
dao.updateJobStatus(Integer.valueOf(jobid), 1);
}
}
}
return result;
}
@RequestMapping("/stop")
public String remove(String jobid) throws ClassNotFoundException, SchedulerException {
Scheduler sche = s.getScheduler();
String result = "";
long times = System.currentTimeMillis();
String t = String.valueOf(times/1000);
HttpSession s = getSession();
if(s.getAttribute("userid")==null){result = "redirect:/adminlogin";}else{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JobDao dao = (JobDao)context.getBean("jobdao");
List<Crons> jobs= dao.queryByjobId(Integer.valueOf(jobid));
if(!jobs.isEmpty()){
if(isStart(jobs.get(0).getJobName()))
{
Task.removeJob(sche, jobs.get(0).getJobName());
dao.updateJobStatus(Integer.valueOf(jobid), 0);
result = "redirect:/jobAll";
System.out.println("任务关闭:"+jobs.get(0).getJobName());
}
}
}
return result;
}
//@RequestMapping("/status")
public boolean isStart(String name) throws SchedulerException, ClassNotFoundException {
boolean fleg = false;
Scheduler sche = s.getScheduler();
JobKey k = new JobKey(name,"JOB_GROUP_SYSTEM");
JobDetail jobDetail = sche.getJobDetail(k);
if(jobDetail==null) {
fleg = false;
}else {
fleg = true;;
}
return fleg;
}
public static HttpSession getSession() {
HttpSession session = null;
try {
session = getRequest().getSession();
} catch (Exception e) {}
return session;
}
public static HttpServletRequest getRequest() {
ServletRequestAttributes attrs =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attrs.getRequest();
}
}
8.创建表结构
CREATE TABLE `job` (
`jobId` int(11) NOT NULL AUTO_INCREMENT,
`jobName` varchar(255) DEFAULT NULL,
`targetClassName` varchar(255) DEFAULT NULL,
`cronExpression` varchar(255) DEFAULT NULL,
`jobStatus` tinyint(3) DEFAULT '0',
`runOnHoliday` varchar(255) DEFAULT NULL,
`jobDesc` varchar(255) DEFAULT NULL,
`createTime` int(11) DEFAULT NULL,
`createrName` varchar(255) DEFAULT NULL,
`updateTime` int(11) DEFAULT NULL,
`updaterName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`jobId`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8
以上已经完成 至于中间的bean在这
package bean;
public class Crons {
private Integer jobId;
private String jobName;
private String targetClassName;
private String cronExpression;
private Integer jobStatus;
private String runOnHoliday;
private String jobDesc;
private Integer createTime;
private String createrName;
private Integer updateTime;
private String updaterName;
public Integer getJobId() {
return jobId;
}
public void setJobId(Integer jobId) {
this.jobId = jobId;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getTargetClassName() {
return targetClassName;
}
public void setTargetClassName(String targetClassName) {
this.targetClassName = targetClassName;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public Integer getJobStatus() {
return jobStatus;
}
public void setJobStatus(Integer jobStatus) {
this.jobStatus = jobStatus;
}
public String getRunOnHoliday() {
return runOnHoliday;
}
public void setRunOnHoliday(String runOnHoliday) {
this.runOnHoliday = runOnHoliday;
}
public String getJobDesc() {
return jobDesc;
}
public void setJobDesc(String jobDesc) {
this.jobDesc = jobDesc;
}
public Integer getCreateTime() {
return createTime;
}
public void setCreateTime(Integer createTime) {
this.createTime = createTime;
}
public String getCreaterName() {
return createrName;
}
public void setCreaterName(String createrName) {
this.createrName = createrName;
}
public Integer getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Integer updateTime) {
this.updateTime = updateTime;
}
public String getUpdaterName() {
return updaterName;
}
public void setUpdaterName(String updaterName) {
this.updaterName = updaterName;
}
}
为了方便大家学习我也就直接把源代码站上了,仅供大家参考学习
我也是在项目里面用到的以下是效果


以上真实效果我只是做了定时导入数据的操作。希望以上内容对大家有所帮助
springMVC的定时器的更多相关文章
- springmvc之定时器
一.通过注解方式实现定时器 1.工程结构 2.所需jar包 3.spring-config.xml,springmvc配置文件 <?xml version="1.0" enc ...
- springMVC实现定时器
//springmvc.xml文件配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns ...
- SpringMVC中定时器继承Task后无法对service注入问题
最近在做一个Spring+MyBatis的一个项目,其中用到了Redis的存储,然后遇到问题是这样的: RedisTask是通过定时器来每分钟像数据库里推送的,于是就有了 public class R ...
- Spring集成Memcached三种方式(一)
转载:http://blog.csdn.net/u013725455/article/details/52102170 Memcached Client目前有3种: Memcached Client ...
- spring核心及常用技术
一.核心内容 1.依赖注入(控制反转) 1)什么是依赖注入 spring将实例的创建交给spring容器(BeanFactory或ApplicationContext)管理,当实例创建后通过设值或构造 ...
- Memcached与Spring集成的方式(待实践)
主要是基于这几种方式http://www.cnblogs.com/EasonJim/p/7624822.html去实现与Spring集成,而个人建议使用Xmemcached去集成好一些,因为现在官方还 ...
- SpringMVC中使用Cron表达式的定时器
SpringMVC中使用Cron表达式的定时器 cron(定时策略)简要说明 顺序: 秒 分 时 日 月 星期 年份 (7个参数,空格隔开各个参数,年份非必须参数) 通配符: , 如果分钟位置为* 1 ...
- SpringMvc定时器任务
在最近的工作中,涉及到一个定时任务,由于以前对springMVC使用较少,所以,上网找了一点资料.这个demo感觉挺好,推荐给大家. 使用到的JAR文件: aopalliance-1.0.jarcom ...
- Springmvc 定时器的实现
有时候会需要项目中,定时去执行一些东西,这个时候就需要用到定时器了.比较简单, 当你springmvc环境搭建成功的时候. 本文转载自:https://www.cnblogs.com/wqj-blog ...
- springMVC + quartz实现定时器(任务调度器)
首先我们要知道任务调度器(定时器)有几种,这边我会写三种 第一种是基于JDK的本身的一个定时器(优点:简单,缺点:满足不了复杂的需求) package com.timer1; import java. ...
随机推荐
- vs code + miktex配置
windows10系统通过choco安装miktex choco install miktex 添加path vscode配置: { // Latex workshop "latex-wor ...
- R6-1 输入年份和天数,输出对应的年、月、日
R6-1 输入年份和天数,输出对应的年.月.日 分数 15 全屏浏览题目 切换布局 作者 张泳 单位 浙大城市学院 要求定义和调用函数month_day ( year, yeardy, *****pm ...
- elasticSearch(五)--排序
1.字段值排序 2.多级排序 3.字符串参数排序 GET /_search?sort=date:desc&sort=_score&q=search
- vivado2018.2封装普通IP模块
将代码打包为一个IP模块 以FIFO代码为例:https://www.cnblogs.com/waqdgstd/p/15267726.html 1.打开向导 2.源文件和外围接口选择,这里不选AXI4 ...
- PR / PO审批
PR审批的BAPI 1.单个项目PR审批 CALL FUNCTION 'BAPI_REQUISITION_RELEASE' EXPORTING number = l_banfn rel_code = ...
- go中的Itoa、Atoi和iota
1. strcov包中的 Itoa 和Atoi Itoa (用于将整数转换为字符串) 来源:早期c语言中没有string类型而是用字符数组array表示字符串,所以 Itoa 是缩写于Int to A ...
- I2C总线简介-转载
I2C总线简介 - 立创社区 (szlcsc.com) 简介 NXP半导体(原Philips半导体)于20多年前发明了一种简单的双向二线制串行通信总线,这个总线这个总线被称为IIC.Inter-IC或 ...
- 11 个Chrome骚技巧让你为所欲为
1.曾经,在线调伪类样式困扰过你? 2.源代码快速定位到某一行 ctrl + p 3.联调接口失败时,后台老哥总管你要 response? 4.你还一层层展开 dom:Alt + Click 5.是不 ...
- c语言中位运算符及用法 异或
a&b: 00000000 00000000 a&b=0x0 a|b : 00000000 01011111 a|b=0x5f a^b : 00000000 01011111 ...
- 通过n个线程顺序打印26个英文字母
通过n个线程顺序打印26个英文字母,例如 n=3 则输出: thread0: a thread1: b thread2: c thread0: d 方案一:轮询 多个线程不断轮询是否是该线程执行任务. ...