前言java
該系統使用場景:git
在12306上買了一張火車票,30分鐘內須要支付(須要添加一個倒計時),30分鐘尚未支付就請求取消訂單的接口(自動根據url請求),若是支付了收到了支付的回調通知後,就刪除計時器上的該任務
1.項目結構圖 json
2.引入所須要依賴的jar包app
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
3.編寫如下類:maven
3.1Config.javaide
public class Config {
public static String token="liujun";
private Config() {
super();
}
}
3.2 JobGroupInfo.javapost
public class JobGroupInfo {
private String jobName;//任務名字
private String jobGroupName;//組名字
private Long nextFireTime;//下次執行時間
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getJobGroupName() {
return jobGroupName;
}
public void setJobGroupName(String jobGroupName) {
this.jobGroupName = jobGroupName;
}
public Long getNextFireTime() {
return nextFireTime;
}
public void setNextFireTime(Long nextFireTime) {
this.nextFireTime = nextFireTime;
}
public JobGroupInfo() {
super();
}
public JobGroupInfo(String jobName, String jobGroupName, Long nextFireTime) {
super();
this.jobName = jobName;
this.jobGroupName = jobGroupName;
this.nextFireTime = nextFireTime;
}
}
3.3 TaskInfo.java測試
public class TaskInfo {
private String backUrl;//任務回調地址
private String jobName;//任務名字
private Integer seconds;//計時時間
private Object context;//其餘內容
private Integer errormaxcount;//失敗請求的次數
private String jobGorupName;//任務組名字
public String getBackUrl() {
return backUrl;
}
public void setBackUrl(String backUrl) {
this.backUrl = backUrl;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public Integer getSeconds() {
return seconds;
}
public void setSeconds(Integer seconds) {
this.seconds = seconds;
}
public Object getContext() {
return context;
}
public void setContext(Object context) {
this.context = context;
}
public Integer getErrormaxcount() {
return errormaxcount;
}
public void setErrormaxcount(Integer errormaxcount) {
this.errormaxcount = errormaxcount;
}
public String getJobGorupName() {
return jobGorupName;
}
public void setJobGorupName(String jobGorupName) {
this.jobGorupName = jobGorupName;
}
public TaskInfo() {
super();
}
public TaskInfo(String backUrl, String jobName, Integer seconds,
Object context, Integer errormaxcount, String jobGorupName) {
super();
this.backUrl = backUrl;
this.jobName = jobName;
this.seconds = seconds;
this.context = context;
this.errormaxcount = errormaxcount;
this.jobGorupName = jobGorupName;
}
@Override
public String toString() {
return "TaskInfo [backUrl=" + backUrl + ", jobName=" + jobName
+ ", seconds=" + seconds + ", context=" + context
+ ", errormaxcount=" + errormaxcount + ", jobGorupName="
+ jobGorupName + "]";
}
}
3.4 JobBack.javathis
public class JobBack implements Job{
//回調執行方法
public void execute(JobExecutionContext context) throws JobExecutionException {
//獲得添加任務中的參數
TaskInfo task = (TaskInfo) context.getMergedJobDataMap().get("task");
sendBack(task);
}
private void sendBack(TaskInfo task) {
task.setErrormaxcount(task.getErrormaxcount() - 1);
// 獲得參數請求回調
try {
//拼裝請求地址以及參數
String uri = "jobName=" + task.getJobName() + "&context=" + task.getContext() + "&jobGorupName="
+ task.getJobGorupName() + "¶mkey=" + Md5Util.GetMD5Code(Config.token);
//請求並獲得返回值
String res = HttpUtil.request_post(task.getBackUrl(), uri);
//若是返回值不是「SUCCESS」 就等待10S進行重複請求(此處避免請求失敗就結束請求,參數中傳遞了一個失敗請求次數)
if (!res.trim().equals("SUCCESS")) {
//若是請求錯誤次數還大於0
if (task.getErrormaxcount() >= 1) {
Thread.sleep(10000);
sendBack(task);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
if (task.getErrormaxcount() >= 1) {
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
sendBack(task);
}
}
}
}
3.5 JobManger.java編碼
public class JobManger {
private final static String TRIGGER_GROUP_NAME = "QUARTZ_TRIGGERGROUP";//觸發器組
private final static SchedulerFactory sf = new StdSchedulerFactory();
/**
* 添加任務
* @param jobName 任務名稱
* @param job 任務處理類 須要繼承Job
* @param context 處理任務能夠獲取的上下文 經過context.getMergedJobDataMap().getString("context"); 獲取
* @param seconds 間隔秒
* @return
*/
public static int addJob(String jobName, Class<? extends Job> job, Object task, int seconds, String jobGorupName){
try {
//判斷任務是否存在
Scheduler sche = sf.getScheduler();
JobKey jobKey = JobKey.jobKey(jobName,jobGorupName);
if(sche.checkExists(jobKey)){
return 1;//任務已經存在
}
//建立一個JobDetail實例,指定SimpleJob
Map<String, Object> JobDetailmap =new HashMap<String, Object>();
JobDetailmap.put("name", jobName);//設置任務名字
JobDetailmap.put("group", jobGorupName);//設置任務組
JobDetailmap.put("jobClass",job.getCanonicalName());//指定執行類 Task.class.getCanonicalName()
JobDetail jobDetail= JobDetailSupport.newJobDetail(JobDetailmap);
//添加數據內容
jobDetail.getJobDataMap().put("task",task);//傳輸的上下文
//經過SimpleTrigger定義調度規則:立刻啓動,每2秒運行一次,共運行100次 等。。。。
SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
simpleTrigger.setName(jobName);
simpleTrigger.setGroup(TRIGGER_GROUP_NAME);
//何時開始執行
simpleTrigger.setStartTime(new Date(new Date().getTime()+1000*seconds));
//間隔時間
simpleTrigger.setRepeatInterval(1000*seconds);
//最多訪問次數 默認執行一次
simpleTrigger.setRepeatCount(0);
//經過SchedulerFactory獲取一個調度器實例
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.scheduleJob(jobDetail, simpleTrigger);//④ 註冊並進行調度
scheduler.start();//⑤調度啓動
return 0;//添加成功
} catch (Exception e) {
return 2;//操做異常
}
}
/**
* 關閉任務調度
* @param jobName 任務名稱
* @return 0 關閉成功 1: 關閉失敗 2:操做異常
*/
public static int closeJob(String jobName,String jobGorupName){
//關閉任務調度
try {
Scheduler sche = sf.getScheduler();
JobKey jobKey = JobKey.jobKey(jobName,jobGorupName);
return sche.deleteJob(jobKey)==true?0:1;
} catch (SchedulerException e) {
return 2;
}
}
private JobManger() {}
}
3.6 AddJob.java
@WebServlet("/addJob.do")
public class AddJob extends HttpServlet{
private static final long serialVersionUID = 1L;
public AddJob() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//避免get 請求
response.sendError(403);
// doPost(request, response);
}
/**
* 處理添加任務
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 設置編碼
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("utf-8");
// 獲得請求
String jobName = request.getParameter("jobName");// 獲得任務名稱
// 獲得token
//String token = request.getParameter("token");
// 驗證簽名
/*if (!MD5Util.GetMD5Code(jobName + Config.token + "zhangke is shabi!").equals(token)) {
return;
}*/
// 獲得回調
String backUrl = request.getParameter("backUrl");
// 獲得請求定時時間
Integer seconds = Integer.valueOf(request.getParameter("seconds"));
String errMaxCount = request.getParameter("errormaxcount");
Integer errormaxcount = errMaxCount == null ? 1 : Integer.valueOf(errMaxCount);// 回調請求失敗的次數
// 默認爲一次
// 獲得其餘參數
String context = request.getParameter("context");
// 獲得任務組
String jobGorupName = request.getParameter("jobGorupName");
TaskInfo t = new TaskInfo(backUrl, jobName, seconds, context, errormaxcount, jobGorupName);
// 添加任務
Integer res = JobManger.addJob(jobName, JobBack.class, t, seconds, jobGorupName);
response.getWriter().write(res.toString());
}
}
3.7 MonitoringJob.java
@WebServlet("/monitoringJob.do")
public class MonitoringJob extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MonitoringJob() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/json;char=utf-8");
// 獲得任務組名字
String jobGroupName = request.getParameter("jobGroupName");
// 驗證是否爲空
//monitoringJob.do
List<JobGroupInfo> list=new ArrayList<JobGroupInfo>();
try {
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(jobGroupName==null?"":jobGroupName))) {
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
// get job's trigger
List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
Date nextFireTime = triggers.get(0).getNextFireTime(); // 下一次執行時間、
JobGroupInfo gri=new JobGroupInfo(jobName, jobGroup, nextFireTime.getTime());
list.add(gri);
}
response.getWriter().write(JSONArray.fromObject(list).toString());
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
3.8 RemoveJob.java
@WebServlet("/removeJob.do")
public class RemoveJob extends HttpServlet {
private static final long serialVersionUID = 1L;
public RemoveJob() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendError(403);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲得任務名
String jobName=request.getParameter("jobName");
//獲得簽名
String token =request.getParameter("token");
//獲得任務組
String jobGorupName=request.getParameter("jobGorupName");
//驗證簽名
/*if(!MD5Util.GetMD5Code(jobName+Config.token+"zhangke is sb!").equals(token)){
response.getWriter().write("2");
return;
}*/
//執行移除操做
int res= JobManger.closeJob(jobName,jobGorupName);
if(res==0){//成功
response.getWriter().write("0");
}else if(res==1){//不存在
response.getWriter().write("1");
}else{
//報錯啦!
response.getWriter().write("2");
}
}
}
3.9 TestBack.java
@WebServlet("/testback")
public class TestBack extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestBack() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get請求");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Map<String, String[]> map=request.getParameterMap();
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String key=iter.next();
System.out.println("key:"+key+" value:"+map.get(key)[0]);
}
response.getWriter().write("SUCCESS");
}
}
3.10 HttpUtil.java
public class HttpUtil {
public static String request_get(String httpUrl) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(20000);
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String request_post(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(20000);
connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
3.11 Md5Util.java
public class Md5Util {
private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public Md5Util() {
}
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return strDigits[iD1] + strDigits[iD2];
}
private static String byteToNum(byte bByte) {
int iRet = bByte;
System.out.println("iRet1=" + iRet);
if (iRet < 0) {
iRet += 256;
}
return String.valueOf(iRet);
}
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}
public static String GetMD5Code(String strObj) {
String resultString = null;
try {
resultString = new String(strObj);
MessageDigest md = MessageDigest.getInstance("MD5");
resultString = byteToString(md.digest(strObj.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}
}
4.啓動maven
https://blog.csdn.net/nandao158/article/details/80902193
5.測試 postman
5秒後看控制檯