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;
}

}

為了方便大家學習我也就直接把源代碼站上了,僅供大家參考學習

我也是在項目里面用到的以下是效果

 

以上真實效果我只是做了定時導入數據的操作。希望以上內容對大家有所幫助


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM