大家好,本人从事软件行业已有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的定时器的更多相关文章

  1. springmvc之定时器

    一.通过注解方式实现定时器 1.工程结构 2.所需jar包 3.spring-config.xml,springmvc配置文件 <?xml version="1.0" enc ...

  2. springMVC实现定时器

    //springmvc.xml文件配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns ...

  3. SpringMVC中定时器继承Task后无法对service注入问题

    最近在做一个Spring+MyBatis的一个项目,其中用到了Redis的存储,然后遇到问题是这样的: RedisTask是通过定时器来每分钟像数据库里推送的,于是就有了 public class R ...

  4. Spring集成Memcached三种方式(一)

    转载:http://blog.csdn.net/u013725455/article/details/52102170 Memcached Client目前有3种: Memcached Client ...

  5. spring核心及常用技术

    一.核心内容 1.依赖注入(控制反转) 1)什么是依赖注入 spring将实例的创建交给spring容器(BeanFactory或ApplicationContext)管理,当实例创建后通过设值或构造 ...

  6. Memcached与Spring集成的方式(待实践)

    主要是基于这几种方式http://www.cnblogs.com/EasonJim/p/7624822.html去实现与Spring集成,而个人建议使用Xmemcached去集成好一些,因为现在官方还 ...

  7. SpringMVC中使用Cron表达式的定时器

    SpringMVC中使用Cron表达式的定时器 cron(定时策略)简要说明 顺序: 秒 分 时 日 月 星期 年份 (7个参数,空格隔开各个参数,年份非必须参数) 通配符: , 如果分钟位置为* 1 ...

  8. SpringMvc定时器任务

    在最近的工作中,涉及到一个定时任务,由于以前对springMVC使用较少,所以,上网找了一点资料.这个demo感觉挺好,推荐给大家. 使用到的JAR文件: aopalliance-1.0.jarcom ...

  9. Springmvc 定时器的实现

    有时候会需要项目中,定时去执行一些东西,这个时候就需要用到定时器了.比较简单, 当你springmvc环境搭建成功的时候. 本文转载自:https://www.cnblogs.com/wqj-blog ...

  10. springMVC + quartz实现定时器(任务调度器)

    首先我们要知道任务调度器(定时器)有几种,这边我会写三种 第一种是基于JDK的本身的一个定时器(优点:简单,缺点:满足不了复杂的需求) package com.timer1; import java. ...

随机推荐

  1. zookeeper(1)-集群的搭建

    集群搭建 1. 下载二进制文件 $ wget --no-check-certificate https://mirrors.ustc.edu.cn/apache/zookeeper/zookeeper ...

  2. Error building Player because scripts had compiler errors

    报错信息如下: Error building Player because scripts had compiler errors Build completed with a result of ' ...

  3. 解题报告:Codeforces 768B Code For 1

    Codeforces 768B Code For 1 题义 有一个序列,刚开始,只有1个数\(n\),接着按照以下规则变化找到序列中任意一个\(>1\)的数\(p\),将他变为 \(\lfloo ...

  4. Google在线深度学习神器Colab——科研角色

    转载:Google在线深度学习神器Colab - 简书 (jianshu.com) 转载:不FQ,免费使用带GPU和TPU的深度学习开发环境_colab (sohu.com)

  5. maven 通用pom.xml

    1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http:// ...

  6. constexpr和const

    const表示一个变量的值不能改变,这个值可以使运行期间得到的const int sz = get_size(); constexpr是提示编译器,该值可以在编译期间就计算出来,并进行替换,不用等到运 ...

  7. Python3 学习基础知识

    python是动态语言(对象属性可以动态改变,删除添加..),不是强类型语言,所以和java,c/c++等强类型静态语言有不一样地方需要注意. 一:基本数据类型 变量 counter = 1   # ...

  8. 串口USART(续二)

    通过前面的分析知道,在LPC824中,USART所拥有的配置寄存器有很多,但在一般情况下,如果只是简单地使用收发功能,则只需要使用到配置寄存器CFG.波特率发生器寄存器BRG.中断使能读取和置位寄存器 ...

  9. java第六周学习情况

    这个星期接到了要开学的消息,心情是非常慌张的,毕竟还没有学到多少东西.但确实是要开学了.心中说不出激动还是紧张,那就带着这种奇妙的情绪记录这次的学习吧 首先必然还是看了相关的程序,记没记下来是另外一说 ...

  10. 学python有了这些书你还担心有什么学不会的吗

    百度云盘:Python高级编程PDF高清完整版书籍免费下载 提取码:bn9d 内容简介  · · · · · · <Python高级编程>通过大量的实例,介绍了Python语言的最佳实践和 ...