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

任务执行定时调度bug修复

wudingsheng пре 1 година
родитељ
комит
48c9332ba8

+ 6 - 0
pom.xml

@@ -241,6 +241,12 @@
             <artifactId>okhttp</artifactId>
             <version>4.9.3</version>
         </dependency>
+        <dependency>
+            <groupId>com.squareup.okio</groupId>
+            <artifactId>okio</artifactId>
+            <version>2.8.0</version>
+        </dependency>
+
 
 
     </dependencies>

+ 9 - 4
src/main/java/com/imcs/admin/business/job/ScheduledPlan.java

@@ -10,6 +10,7 @@ import com.imcs.admin.entity.WWarehouseManagement;
 import com.imcs.admin.util.DateUtils;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
+import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Component;
 
 import java.util.Date;
@@ -28,19 +29,19 @@ public class ScheduledPlan extends BaseServiceImpl {
      * 出入库任务定时调度
      * @throws Exception
      */
-    //@Scheduled(cron = "0/10 * 1 * * *")
+    //@Scheduled(cron = "0/10 * * * * *")
     public void startPlan() throws Exception{
         LambdaQueryWrapper<WPInventoryCountPlan> wrapper = Wrappers.lambdaQuery(WPInventoryCountPlan.class).eq(WPInventoryCountPlan::getStatus, 1);
         List<WPInventoryCountPlan> wpInventoryCountPlans = wPInventoryCountPlanDao.selectList(wrapper);
 
         wpInventoryCountPlans.stream().forEach(vo->{
-            if(vo.getPlanStrategy().intValue() == 7){
+            if(vo.getPlanStrategy() == 7){
                 String dayOfWeek = DateUtils.getDayOfWeek(vo.getPlanTime());
                 String nowOfWeek = DateUtils.getDayOfWeek(new Date());
                 if(StringUtils.equals(dayOfWeek,nowOfWeek)){
                     createTask(vo.getId());
                 }
-            }else if(vo.getPlanStrategy().intValue() == 30){
+            }else if(vo.getPlanStrategy() == 30){
                 Boolean dateInCurrentMonth = DateUtils.isDateInCurrentMonth(vo.getPlanTime());
                 int i = DateUtils.nowDay(new Date());
                 int i1 = DateUtils.nowDay(vo.getPlanTime());
@@ -54,9 +55,11 @@ public class ScheduledPlan extends BaseServiceImpl {
                         createTask(vo.getId());
                     }
                 }
-            }else if(vo.getPlanStrategy().intValue() == 365){
+            }else if(vo.getPlanStrategy() == 365){
                 String monthAndDay = DateUtils.getMonthAndDay(vo.getPlanTime());
                 String nowMonthAndDay = DateUtils.getMonthAndDay(new Date());
+
+                //TODO 如果是闰年 可能有问题
                 if(StringUtils.equals(monthAndDay,nowMonthAndDay)){
                     createTask(vo.getId());
                 }
@@ -66,6 +69,8 @@ public class ScheduledPlan extends BaseServiceImpl {
         });
     }
 
+
+
     public  void createTask(Long id){
         WPInventoryCountTask wpInventoryCountTask=new WPInventoryCountTask();
         wpInventoryCountTask.setTaskCode(generateSerial.generateSerialNumber("planTaskCode"));

+ 85 - 38
src/main/java/com/imcs/admin/business/job/ScheduledTask.java

@@ -1,7 +1,12 @@
 package com.imcs.admin.business.job;
 
 import cn.hutool.core.lang.Assert;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
 import com.imcs.admin.business.constants.Status;
 import com.imcs.admin.business.dao.WApiCallRecordsDao;
 import com.imcs.admin.business.service.impl.BaseServiceImpl;
@@ -21,9 +26,15 @@ import org.springframework.stereotype.Component;
 
 import okhttp3.Request;
 import okhttp3.Response;
+
 import java.io.IOException;
+
 import okhttp3.MediaType;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
 
+import java.io.PrintWriter;
+import java.io.StringWriter;
 import java.util.Date;
 import java.util.List;
 import java.util.Objects;
@@ -33,6 +44,7 @@ import java.util.Objects;
  */
 @Slf4j
 @Component
+@RestController("/ScheduledTask")
 public class ScheduledTask extends BaseServiceImpl {
 
 
@@ -41,77 +53,112 @@ public class ScheduledTask extends BaseServiceImpl {
 
     /**
      * 出入库任务定时调度
+     *
      * @throws Exception
      */
     //@Scheduled(cron = "*/10 * * * * *")
-    public void startTask() throws Exception{
+    @GetMapping("/startTask")
+    public void startTask() throws Exception {
         //查出task表id最小的一条status= 0 1 的数据
         //查这条数据任务,按照子任务顺序id最小开始依次执行
-        //如果任务还未开始和异常,则调C#接口
-        /*Object apiTask = redisTemplate.opsForValue().get("API_TASK_ERROR");
-        if(!Objects.isNull(apiTask)){
-            return;
-        }*/
+        //如果任务状态是 未开始 或 异常,则调C#接口
         Object jobLock = redisTemplate.opsForValue().get("JOB_LOCK");
-        if(!Objects.isNull(jobLock)){
+        if (!Objects.isNull(jobLock)) {
             return;
         }
         WInventoryTransactionTask wInventoryTransactionTask = taskDao.selectOne();
-        Assert.isNull(wInventoryTransactionTask);
+        Assert.notNull(wInventoryTransactionTask);
         List<WInventoryTransactionChildTask> wInventoryTransactionTaskDetails = childTaskDao.selectListByTaskId(wInventoryTransactionTask);
-        if(CollectionUtils.isNotEmpty(wInventoryTransactionTaskDetails)){
+        if (CollectionUtils.isNotEmpty(wInventoryTransactionTaskDetails)) {
             WInventoryTransactionChildTask wInventoryTransactionChildTask = wInventoryTransactionTaskDetails.get(0);
-            if(wInventoryTransactionChildTask.getStatus() == Status.NOT_STARTED.getCode() || wInventoryTransactionChildTask.getStatus() == Status.EXCEPTION.getCode()){
-                redisTemplate.opsForValue().set("JOB_LOCK",true);
+            if (wInventoryTransactionChildTask.getStatus() == Status.NOT_STARTED.getCode() || wInventoryTransactionChildTask.getStatus() == Status.EXCEPTION.getCode()) {
+                redisTemplate.opsForValue().set("JOB_LOCK", true);
                 httpHandler(wInventoryTransactionChildTask);
             }
         }
     }
 
     private void httpHandler(WInventoryTransactionChildTask item) {
-
-        OkHttpClient okHttpClient=new OkHttpClient();
+        String responseBody = null;
+        Date responseTime = null;
+        String url = "http://127.0.0.1:8081";
+        Date requestTime = new Date();
         String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
-        RequestBody body = RequestBody.create(json,JSON);
-        String url="";
-        Date requestTime=new Date();
-        Request request = new Request.Builder()
-                .url(url)
-                .post(body)
-                .build();
-
-        try (Response response = okHttpClient.newCall(request).execute()) {
-            Date responseTime=new Date();
-            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+        try {
+            OkHttpClient okHttpClient = new OkHttpClient();
 
-            // 获取响应体
-            String responseBody = response.body().string();
+            RequestBody body = RequestBody.create(json, JSON);
 
-            //TODO 修改任务状态
-            //update 
 
-            insertApiLog(json,responseBody,url,requestTime,responseTime);
+            Request request = new Request.Builder()
+                    .url(url)
+                    .post(body)
+                    .build();
 
+            //Response response = okHttpClient.newCall(request).execute();
+            responseTime = new Date();
+            //if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
-        } catch (IOException e) {
-            log.error("调用接口失败:",e);
-            throw new RuntimeException();
-        }finally {
-            redisTemplate.opsForValue().decrement("JOB_LOCK");
+            // 获取响应体
+            //responseBody = response.body().string();
+            responseBody = "{\"success\":true,\"errmsg\":\"123\"}";
+
+
+            JsonObject jsonObject = JsonParser.parseString(responseBody).getAsJsonObject();
+
+            // 修改任务状态
+            if (jsonObject.get("success").getAsBoolean()) {
+                item.setStatus(Status.IN_PROGRESS_TASK.getCode());
+                childTaskDao.updateById(item);
+
+                LambdaQueryWrapper<WInventoryTransactionChildTask> wrapper = new LambdaQueryWrapper<>();
+                wrapper.eq(WInventoryTransactionChildTask::getWInventoryTransactionTaskId, item.getWInventoryTransactionTaskId());
+
+                List<WInventoryTransactionChildTask> wInventoryTransactionChildTasks = childTaskDao.selectList(wrapper);
+
+                long count = wInventoryTransactionChildTasks.stream().filter(it -> it.getStatus() == Status.IN_PROGRESS_TASK.getCode()).count();
+                //修改任务开始时间   结束时间应该在wcs调wms,任务真正完成之后修改
+                if (count == 1) {
+                    WInventoryTransactionTask wInventoryTransactionTask=new WInventoryTransactionTask();
+                    wInventoryTransactionTask.setId(item.getWInventoryTransactionTaskId());
+                    wInventoryTransactionTask.setStartTime(new Date());
+                    wInventoryTransactionTask.setStatus(Status.IN_PROGRESS_TASK.getCode());
+                    taskDao.update( wInventoryTransactionTask);
+                }
+            } else {
+                item.setStatus(Status.EXCEPTION.getCode());
+                //wcs异常返回原因
+                item.setErrorInfo(jsonObject.get("errmsg").getAsString());
+                childTaskDao.updateById(item);
+            }
+
+        } catch (Exception e) {
+            log.error("调用接口失败:", e);
+            responseTime = new Date();
+            StringWriter sw = new StringWriter();
+            PrintWriter pw = new PrintWriter(sw);
+            e.printStackTrace(pw);
+            responseBody = sw.toString();
+        } finally {
+            redisTemplate.opsForValue().getAndDelete("JOB_LOCK");
             log.error("释放定时任务调度锁");
+            insertApiLog(json, responseBody, url, requestTime, responseTime, item);
         }
     }
 
-    private void insertApiLog(String json, String responseBody,String url,Date requestTime,Date responseTime) {
-        WApiCallRecords wApiCallRecords=new WApiCallRecords();
-        JsonObject gson=new JsonObject();
-        JsonObject asJsonObject = gson.getAsJsonObject(responseBody);
+    private void insertApiLog(String json, String responseBody, String url, Date requestTime, Date responseTime, WInventoryTransactionChildTask item) {
+        WApiCallRecords wApiCallRecords = new WApiCallRecords();
+        // 创建 Gson 实例
+        Gson gson = new Gson();
+
         wApiCallRecords.setApiName("ApiName");
         wApiCallRecords.setEndpoint(url);
         wApiCallRecords.setMethod("get");
         wApiCallRecords.setRequestBody(json);
         wApiCallRecords.setResponseBody(responseBody);
         wApiCallRecords.setRequestTime(requestTime);
+        wApiCallRecords.setChildTaskId(item.getId());
+        wApiCallRecords.setChildTaskJson(gson.toJson(item));
         wApiCallRecords.setResponseTime(responseTime);
         wApiCallRecords.setCreatedAt(new Date());
         wApiCallRecordsDao.insert(wApiCallRecords);

+ 7 - 0
src/main/java/com/imcs/admin/common/config/AdminInterceptor.java

@@ -12,6 +12,8 @@ import org.springframework.web.servlet.HandlerInterceptor;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.util.Arrays;
+import java.util.List;
 
 /**
  * @author zhuhao
@@ -23,9 +25,14 @@ public class AdminInterceptor implements HandlerInterceptor {
 //    @Resource
 //    @Lazy
 //    SessionContext sessionContext;
+
+    private static final List<String> EXCLUDED_URLS = Arrays.asList("/startTask");
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         log.info("拦截url:"+request.getRequestURI());
+        if(EXCLUDED_URLS.contains(request.getRequestURI())){
+            return true;
+        }
         String uri = request.getRequestURI();
         SessionContext sessionContext = SpringContextUtil.getBean(SessionContext.class);
         UserSession userSession = sessionContext.getSession(request);

+ 3 - 0
src/main/java/com/imcs/admin/entity/WApiCallRecords.java

@@ -67,6 +67,9 @@ public class WApiCallRecords implements Serializable {
      */
     private Date updatedAt;
 
+    private Long childTaskId;
+
+    private String childTaskJson;
 
 }
 

+ 0 - 1
src/main/java/com/imcs/admin/entity/WInventoryTransactionTask.java

@@ -29,7 +29,6 @@ public class WInventoryTransactionTask extends PageSize implements Serializable
 /**
      * 出入库单ID
      */
-@TableField(value = "w_inventory_transaction_orders_id")
     private Long wInventoryTransactionOrdersId;
 /**
      * 出入库任务编码