Преглед изворни кода

添加任务超时属性,超时后失败

chuan пре 7 година
родитељ
комит
86acbcd777

+ 1 - 0
doc/db/tables_xxl_job.sql Прегледај датотеку

@@ -158,6 +158,7 @@ CREATE TABLE `XXL_JOB_QRTZ_TRIGGER_INFO` (
158 158
   `update_time` datetime DEFAULT NULL,
159 159
   `author` varchar(64) DEFAULT NULL COMMENT '作者',
160 160
   `alarm_email` varchar(255) DEFAULT NULL COMMENT '报警邮件',
161
+  `execute_timeout` int(11) NOT NULL DEFAULT 0 COMMENT '任务执行超时时间',
161 162
   `executor_route_strategy` varchar(50) DEFAULT NULL COMMENT '执行器路由策略',
162 163
   `executor_handler` varchar(255) DEFAULT NULL COMMENT '执行器任务handler',
163 164
   `executor_param` varchar(512) DEFAULT NULL COMMENT '执行器任务参数',

+ 11 - 0
xxl-job-admin/src/main/java/com/xxl/job/admin/core/model/XxlJobInfo.java Прегледај датотеку

@@ -36,6 +36,17 @@ public class XxlJobInfo {
36 36
 	// copy from quartz
37 37
 	private String jobStatus;		// 任务状态 【base on quartz】
38 38
 
39
+	private int executeTimeout;     // 任务最多执行时间,超时后报警
40
+
41
+	public int getExecuteTimeout() {
42
+		return executeTimeout;
43
+	}
44
+
45
+	public void setExecuteTimeout(int executeTimeout) {
46
+		this.executeTimeout = executeTimeout;
47
+	}
48
+
49
+
39 50
 	public int getId() {
40 51
 		return id;
41 52
 	}

+ 1 - 0
xxl-job-admin/src/main/java/com/xxl/job/admin/core/thread/JobFailMonitorHelper.java Прегледај датотеку

@@ -63,6 +63,7 @@ public class JobFailMonitorHelper {
63 63
 									logger.info(">>>>>>>>>>> job monitor, job success, JobLogId:{}", jobLogId);
64 64
 								} else if (IJobHandler.FAIL.getCode() == log.getTriggerCode()
65 65
 										|| IJobHandler.FAIL.getCode() == log.getHandleCode()
66
+										|| IJobHandler.TIMEOUT.getCode() == log.getHandleCode()
66 67
 										|| IJobHandler.FAIL_RETRY.getCode() == log.getHandleCode() ) {
67 68
 									// job fail,
68 69
 									failAlarm(log);

+ 3 - 0
xxl-job-admin/src/main/java/com/xxl/job/admin/core/trigger/XxlJobTrigger.java Прегледај датотеку

@@ -96,6 +96,8 @@ public class XxlJobTrigger {
96 96
                     triggerParam.setGlueUpdatetime(jobInfo.getGlueUpdatetime().getTime());
97 97
                     triggerParam.setBroadcastIndex(i);
98 98
                     triggerParam.setBroadcastTotal(addressList.size()); // update02
99
+                    // 执行超时时间
100
+                    triggerParam.setExecuteTimeout(jobInfo.getExecuteTimeout());
99 101
 
100 102
                     // 4.2、trigger-run (route run / trigger remote executor)
101 103
                     triggerResult = runExecutor(triggerParam, address);     // update03
@@ -164,6 +166,7 @@ public class XxlJobTrigger {
164 166
                 triggerParam.setGlueUpdatetime(jobInfo.getGlueUpdatetime().getTime());
165 167
                 triggerParam.setBroadcastIndex(0);
166 168
                 triggerParam.setBroadcastTotal(1);
169
+                triggerParam.setExecuteTimeout(jobInfo.getExecuteTimeout());
167 170
 
168 171
                 // 4.2、trigger-run (route run / trigger remote executor)
169 172
                 triggerResult = executorRouteStrategyEnum.getRouter().routeRun(triggerParam, addressList);

+ 2 - 0
xxl-job-admin/src/main/resources/i18n/message.properties Прегледај датотеку

@@ -107,6 +107,7 @@ jobinfo_field_gluetype=运行模式
107 107
 jobinfo_field_executorparam=任务参数
108 108
 jobinfo_field_cron_unvalid=Cron格式非法
109 109
 jobinfo_field_author=负责人
110
+jobinfo_field_timeout=最大执行时间
110 111
 jobinfo_field_alarmemail=报警邮件
111 112
 jobinfo_field_alarmemail_placeholder=请输入报警邮件,多个邮件地址则逗号分隔
112 113
 jobinfo_field_executorRouteStrategy=路由策略
@@ -157,6 +158,7 @@ joblog_clean_type_9=清理所有日志数据
157 158
 joblog_clean_type_unvalid=清理类型参数异常
158 159
 joblog_handleCode_200=成功
159 160
 joblog_handleCode_500=失败
161
+joblog_handleCode_400=超时
160 162
 joblog_handleCode_501=失败重试
161 163
 joblog_kill_log=终止任务
162 164
 joblog_kill_log_limit=调度失败,无法终止日志

+ 2 - 0
xxl-job-admin/src/main/resources/i18n/message_en.properties Прегледај датотеку

@@ -103,6 +103,7 @@ jobinfo_field_update=Edit Job
103 103
 jobinfo_field_id=Job ID
104 104
 jobinfo_field_jobgroup=Executor
105 105
 jobinfo_field_jobdesc=Job description
106
+jobinfo_field_timeout=Max execute time
106 107
 jobinfo_field_gluetype=GLUE Type
107 108
 jobinfo_field_executorparam=Param
108 109
 jobinfo_field_cron_unvalid=The Cron is illegal
@@ -157,6 +158,7 @@ joblog_clean_type_9=Clean up all log data
157 158
 joblog_clean_type_unvalid=Clean type is illegal
158 159
 joblog_handleCode_200=Success
159 160
 joblog_handleCode_500=Fail
161
+joblog_handleCode_400=Timeout
160 162
 joblog_handleCode_501=Fail retry
161 163
 joblog_kill_log=Kill Job
162 164
 joblog_kill_log_limit=Trigger Fail, can not kill job

+ 20 - 15
xxl-job-admin/src/main/resources/mybatis-mapper/XxlJobInfoMapper.xml Прегледај датотеку

@@ -1,18 +1,18 @@
1 1
 <?xml version="1.0" encoding="UTF-8"?>
2
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
2
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
3 3
 	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
4 4
 <mapper namespace="com.xxl.job.admin.dao.XxlJobInfoDao">
5
-	
5
+
6 6
 	<resultMap id="XxlJobInfo" type="com.xxl.job.admin.core.model.XxlJobInfo" >
7 7
 		<result column="id" property="id" />
8
-	
8
+
9 9
 		<result column="job_group" property="jobGroup" />
10 10
 	    <result column="job_cron" property="jobCron" />
11 11
 	    <result column="job_desc" property="jobDesc" />
12
-	    
12
+
13 13
 	    <result column="add_time" property="addTime" />
14 14
 	    <result column="update_time" property="updateTime" />
15
-	    
15
+
16 16
 	    <result column="author" property="author" />
17 17
 	    <result column="alarm_email" property="alarmEmail" />
18 18
 
@@ -21,11 +21,12 @@
21 21
 	    <result column="executor_param" property="executorParam" />
22 22
 		<result column="executor_block_strategy" property="executorBlockStrategy" />
23 23
 		<result column="executor_fail_strategy" property="executorFailStrategy" />
24
-	    
24
+
25 25
 	    <result column="glue_type" property="glueType" />
26 26
 	    <result column="glue_source" property="glueSource" />
27 27
 	    <result column="glue_remark" property="glueRemark" />
28 28
 		<result column="glue_updatetime" property="glueUpdatetime" />
29
+		<result column="execute_timeout" property="executeTimeout" />
29 30
 
30 31
 		<result column="child_jobid" property="childJobId" />
31 32
 	</resultMap>
@@ -48,9 +49,10 @@
48 49
 		t.glue_source,
49 50
 		t.glue_remark,
50 51
 		t.glue_updatetime,
52
+		t.execute_timeout,
51 53
 		t.child_jobid
52 54
 	</sql>
53
-	
55
+
54 56
 	<select id="pageList" parameterType="java.util.HashMap" resultMap="XxlJobInfo">
55 57
 		SELECT <include refid="Base_Column_List" />
56 58
 		FROM XXL_JOB_QRTZ_TRIGGER_INFO AS t
@@ -68,7 +70,7 @@
68 70
 		ORDER BY id DESC
69 71
 		LIMIT #{offset}, #{pagesize}
70 72
 	</select>
71
-	
73
+
72 74
 	<select id="pageListCount" parameterType="java.util.HashMap" resultType="int">
73 75
 		SELECT count(1)
74 76
 		FROM XXL_JOB_QRTZ_TRIGGER_INFO AS t
@@ -103,10 +105,11 @@
103 105
 			glue_source,
104 106
 			glue_remark,
105 107
 			glue_updatetime,
106
-			child_jobid
108
+			child_jobid,
109
+		    execute_timeout
107 110
 		) VALUES (
108 111
 			#{jobGroup},
109
-			#{jobCron}, 
112
+			#{jobCron},
110 113
 			#{jobDesc},
111 114
 			NOW(),
112 115
 			NOW(),
@@ -121,7 +124,8 @@
121 124
 			#{glueSource},
122 125
 			#{glueRemark},
123 126
 			NOW(),
124
-			#{childJobId}
127
+			#{childJobId},
128
+		    #{executeTimeout}
125 129
 		);
126 130
 		<!--<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
127 131
 			SELECT LAST_INSERT_ID()
@@ -134,10 +138,10 @@
134 138
 		FROM XXL_JOB_QRTZ_TRIGGER_INFO AS t
135 139
 		WHERE t.id = #{id}
136 140
 	</select>
137
-	
141
+
138 142
 	<update id="update" parameterType="com.xxl.job.admin.core.model.XxlJobInfo" >
139 143
 		UPDATE XXL_JOB_QRTZ_TRIGGER_INFO
140
-		SET 
144
+		SET
141 145
 			job_cron = #{jobCron},
142 146
 			job_desc = #{jobDesc},
143 147
 			update_time = NOW(),
@@ -152,10 +156,11 @@
152 156
 			glue_source = #{glueSource},
153 157
 			glue_remark = #{glueRemark},
154 158
 			glue_updatetime = #{glueUpdatetime},
155
-			child_jobid = #{childJobId}
159
+			child_jobid = #{childJobId},
160
+			execute_timeout = ${executeTimeout}
156 161
 		WHERE id = #{id}
157 162
 	</update>
158
-	
163
+
159 164
 	<delete id="delete" parameterType="java.util.HashMap">
160 165
 		DELETE
161 166
 		FROM XXL_JOB_QRTZ_TRIGGER_INFO

+ 5 - 0
xxl-job-admin/src/main/webapp/WEB-INF/template/jobinfo/jobinfo.index.ftl Прегледај датотеку

@@ -169,6 +169,11 @@
169 169
 						<div class="col-sm-4"><input type="text" class="form-control" name="alarmEmail" placeholder="${I18n.jobinfo_field_alarmemail_placeholder}" maxlength="100" ></div>
170 170
 					</div>
171 171
 
172
+					<div class="form-group">
173
+						<label for="lastname" class="col-sm-2 control-label">${I18n.jobinfo_field_timeout}<font color="red">*</font></label>
174
+						<div class="col-sm-4"><input type="text" class="form-control" name="executeTimeout" placeholder="0" maxlength="100" ></div>
175
+					</div>
176
+
172 177
                     <hr>
173 178
 					<div class="form-group">
174 179
 						<div class="col-sm-offset-3 col-sm-6">

+ 1 - 0
xxl-job-admin/src/main/webapp/static/js/jobinfo.index.1.js Прегледај датотеку

@@ -362,6 +362,7 @@ $(function() {
362 362
 		$("#updateModal .form input[name='jobCron']").val( row.jobCron );
363 363
 		$("#updateModal .form input[name='author']").val( row.author );
364 364
 		$("#updateModal .form input[name='alarmEmail']").val( row.alarmEmail );
365
+		$("#updateModal .form input[name='executeTimeout']").val( row.executeTimeout );
365 366
 		$('#updateModal .form select[name=executorRouteStrategy] option[value='+ row.executorRouteStrategy +']').prop('selected', true);
366 367
 		$("#updateModal .form input[name='executorHandler']").val( row.executorHandler );
367 368
 		$("#updateModal .form input[name='executorParam']").val( row.executorParam );

+ 2 - 0
xxl-job-admin/src/main/webapp/static/js/joblog.index.1.js Прегледај датотеку

@@ -159,6 +159,8 @@ $(function() {
159 159
                                 html = '<span style="color: red">'+ I18n.joblog_handleCode_500 +'</span>';
160 160
                             } else if (data == 501) {
161 161
                                 html = '<span style="color: red">'+ I18n.joblog_handleCode_501 +'</span>';
162
+                            } else if (data == 400) {
163
+                                html = '<span style="color: red">'+ I18n.joblog_handleCode_400 +'</span>';
162 164
                             } else if (data == 0) {
163 165
                                 html = '';
164 166
                             }

+ 3 - 0
xxl-job-core/src/main/java/com/xxl/job/core/biz/model/ReturnT.java Прегледај датотеку

@@ -12,8 +12,11 @@ public class ReturnT<T> implements Serializable {
12 12
 
13 13
 	public static final int SUCCESS_CODE = 200;
14 14
 	public static final int FAIL_CODE = 500;
15
+	public static final int EXECUTE_TIMEOUT = 400;
16
+
15 17
 	public static final ReturnT<String> SUCCESS = new ReturnT<String>(null);
16 18
 	public static final ReturnT<String> FAIL = new ReturnT<String>(FAIL_CODE, null);
19
+	public static final ReturnT<String> TIMEOUT = new ReturnT<String>(EXECUTE_TIMEOUT, "执行超时");
17 20
 	
18 21
 	private int code;
19 22
 	private String msg;

+ 10 - 0
xxl-job-core/src/main/java/com/xxl/job/core/biz/model/TriggerParam.java Прегледај датотеку

@@ -24,6 +24,16 @@ public class TriggerParam implements Serializable{
24 24
     private int broadcastIndex;
25 25
     private int broadcastTotal;
26 26
 
27
+    private int executeTimeout;
28
+
29
+    public int getExecuteTimeout() {
30
+        return executeTimeout;
31
+    }
32
+
33
+    public void setExecuteTimeout(int executeTimeout) {
34
+        this.executeTimeout = executeTimeout;
35
+    }
36
+
27 37
     public int getJobId() {
28 38
         return jobId;
29 39
     }

+ 2 - 0
xxl-job-core/src/main/java/com/xxl/job/core/handler/IJobHandler.java Прегледај датотеку

@@ -14,6 +14,8 @@ public abstract class IJobHandler {
14 14
 	public static final ReturnT<String> SUCCESS = new ReturnT<String>(200, null);
15 15
 	/** fail */
16 16
 	public static final ReturnT<String> FAIL = new ReturnT<String>(500, null);
17
+	/** timeout */
18
+	public static final ReturnT<String> TIMEOUT = new ReturnT<String>(400, null);
17 19
 	/** fail retry */
18 20
 	public static final ReturnT<String> FAIL_RETRY = new ReturnT<String>(501, null);
19 21
 

+ 26 - 3
xxl-job-core/src/main/java/com/xxl/job/core/thread/JobThread.java Прегледај датотеку

@@ -16,8 +16,7 @@ import java.io.PrintWriter;
16 16
 import java.io.StringWriter;
17 17
 import java.util.Arrays;
18 18
 import java.util.Date;
19
-import java.util.concurrent.LinkedBlockingQueue;
20
-import java.util.concurrent.TimeUnit;
19
+import java.util.concurrent.*;
21 20
 
22 21
 /**
23 22
  * handler thread
@@ -106,6 +105,7 @@ public class JobThread extends Thread{
106 105
 
107 106
             TriggerParam triggerParam = null;
108 107
             ReturnT<String> executeResult = null;
108
+			ExecutorService singleThread = Executors.newSingleThreadExecutor();
109 109
             try {
110 110
 				// to check toStop signal, we need cycle, so wo cannot use queue.take(), instand of poll(timeout)
111 111
 				triggerParam = triggerQueue.poll(3L, TimeUnit.SECONDS);
@@ -121,7 +121,27 @@ public class JobThread extends Thread{
121 121
 
122 122
 					// execute
123 123
 					XxlJobLogger.log("<br>----------- xxl-job job execute start -----------<br>----------- Param:" + triggerParam.getExecutorParams());
124
-					executeResult = handler.execute(triggerParam.getExecutorParams());
124
+					int executeTimeout = triggerParam.getExecuteTimeout();
125
+
126
+
127
+					final TriggerParam finalTriggerParam = triggerParam;
128
+
129
+					Future<ReturnT<String>> future = singleThread.submit(new Callable<ReturnT<String>>() {
130
+						@Override
131
+						public ReturnT<String> call() throws Exception {
132
+							return handler.execute(finalTriggerParam.getExecutorParams());
133
+						}
134
+					});
135
+
136
+					try {
137
+						if (executeTimeout > 0) {
138
+							executeResult = future.get(executeTimeout, TimeUnit.SECONDS);
139
+						} else {
140
+							executeResult = future.get();
141
+						}
142
+					} catch (TimeoutException timeoutException) {
143
+						executeResult = ReturnT.TIMEOUT;
144
+					}
125 145
 					if (executeResult == null) {
126 146
 						executeResult = IJobHandler.FAIL;
127 147
 					}
@@ -144,6 +164,9 @@ public class JobThread extends Thread{
144 164
 
145 165
 				XxlJobLogger.log("<br>----------- JobThread Exception:" + errorMsg + "<br>----------- xxl-job job execute end(error) -----------");
146 166
 			} finally {
167
+            	if (singleThread != null) {
168
+            		singleThread.shutdown();
169
+				}
147 170
                 if(triggerParam != null) {
148 171
                     // callback handler info
149 172
                     if (!toStop) {