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包

springMVC的定时器

将下载的包放进你的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的定时器

以上真实效果我只是做了定时导入数据的操作。希望以上内容对大家有所帮助