天天看點

如何建立一個定時管理的頁面

實作的效果: 

如何建立一個定時管理的頁面

類似這樣的一個定時管理,對程式的中定時計劃可以動态的控制其運作還是關閉

第一步:建立資料表:

如何建立一個定時管理的頁面

如上圖所示,建立如此資料表即可,而且關鍵的是最後的兩個字段還沒有用到

第二步,頁面:

如何建立一個定時管理的頁面

就是上面的三個頁面,一個添加,一個修改,一個清單頁面

第三步:背景代碼的實作:

package com.hangxin.time.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hangxin.commons.util.PageModel;
import com.hangxin.commons.web.BasicAction;
import com.hangxin.time.model.TaskInfo;
import com.hangxin.time.service.IKpTimeService;
import com.hangxin.xxdzfp.service.PzService;
import com.hangxin.xxdzfp.service.ZpBillService;
import com.hangxin.xxdzfp.util.StrUtil;

@Controller
public class BillTimeAction extends BasicAction
{

    private Logger logger = null;

    @Resource
    protected ZpBillService zpBillServiceImpl;

    @Resource
    protected IKpTimeService kpService;

    @Resource
    protected PzService pzServiceImpl;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private static HashMap<String, ScheduledFuture<?>> map = new HashMap<String, ScheduledFuture<?>>();

    private ScheduledFuture<?> future;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        return executor;
    }

    public BillTimeAction() {
        super();
        logger = Logger.getLogger(BillTimeAction.class);
    }

    /**
     * @author wdg
     * 定時管理頁面的渲染
     */

    @PostConstruct
    public void init() {

        List<TaskInfo> list = kpService.getTaskInfoList();
        for (TaskInfo taskinfo : list) {
            if (taskinfo.getRunstatus() == 1 && taskinfo.getRestartflag() != 1
                    && map.get(taskinfo.getTaskclass()) == null) {
                try {
                    String taskclass = taskinfo.getTaskclass();
                    Class<?> clazz = Class.forName(taskclass);
                    HashMap<String, Object> hmap = new HashMap<String, Object>();
                    hmap.put(ZpBillService.class.getName(), zpBillServiceImpl);
                    hmap.put(IKpTimeService.class.getName(), kpService);
                    hmap.put(PzService.class.getName(), pzServiceImpl);
                    Constructor<?> con = clazz.getConstructor(Map.class);
                    future = threadPoolTaskScheduler.schedule((Runnable) con.newInstance(hmap),
                            new CronTrigger(taskinfo.getCronstr()));
                    map.put(taskclass, future);
                    taskinfo.setRestartflag(1);//項目啟動中啟動成功
                    taskinfo.setRestarttime(new Date());
                    kpService.updateTaskInfo(taskinfo);
                }
                catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (NoSuchMethodException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (InstantiationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }

    }

    @RequestMapping(value = "/BillTimeAction_init")
    public String BillTimeAction_Init(HttpServletRequest request, HttpServletResponse response, Model model) {
        //  Map<String, Object> map = kpService.isUpdateDrInfo();
        PageModel<Map<String, Object>> pageModel = new PageModel<Map<String, Object>>();
        pageModel.setPages(1);// 必須先比pageno設定
        pageModel.setPageNo(1);
        pageModel.setPageSize(20);
        Map<String, Object> map = new HashMap<String, Object>();
        pageModel = kpService.getTaskPageModel(pageModel, map);
        model.addAttribute("pageModel", pageModel);
        model.addAttribute("map", map);
        return "timemanager/tasklist";
    }

    /**
     * @author wdg
     *   新增的定時管理頁面              
     */

    @RequestMapping(value = "/addTaskAction_init")
    public String addTaskAction_Init(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "timemanager/addtask";
    }

    /**
     * @author wdg
     * 修改頁面的初始化
     */
    @RequestMapping(value = "/modifyTaskAction_init")
    public String modifyTaskAction_Init(HttpServletRequest request, HttpServletResponse response, String rowguid,
            Model model) {
        if (StrUtil.isNotBlank(rowguid)) {
            TaskInfo taskinfo = kpService.getTaskInfoByGuid(rowguid);
            model.addAttribute("taskinfo", taskinfo);
        }
        return "timemanager/modifytask";
    }

    /**
     * 
     * @author wdg
     * 新增對應的任務
     */

    @RequestMapping(value = "/addTaskAction")
    public void addTaskAction(@RequestBody Map<String, Object> reqMap, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        //傳遞一個目前開票的比例
        PrintWriter out = null;
        try {
            out = response.getWriter();
        }
        catch (IOException e) {
            logger.info(e.getMessage());
        }
        String msg = "0";
        TaskInfo taskinfo = new TaskInfo();
        taskinfo.setRowguid(UUID.randomUUID().toString());
        taskinfo.setAddtime(new Date());
        taskinfo.setTaskname(reqMap.get("taskname") == null ? "" : reqMap.get("taskname").toString());
        taskinfo.setTaskclass(reqMap.get("taskclass") == null ? "" : reqMap.get("taskclass").toString());
        taskinfo.setCronstr(reqMap.get("cornstr") == null ? "" : reqMap.get("cornstr").toString());
        taskinfo.setRunstatus("1".equals(reqMap.get("runstatus")) ? 1 : 0);
        taskinfo.setRemark(reqMap.get("remark") == null ? "" : reqMap.get("remark").toString());
        //資料檢驗
        if (StrUtil.isNotBlank(taskinfo.getTaskname())) {
            int num = kpService.isExistTaskName(taskinfo.getTaskname());
            if (num > 0) {
                msg = "1";
                out.print(msg);
                return;
            }
        }
        if (StrUtil.isNotBlank(taskinfo.getTaskclass())) {
            int num = kpService.isExistTaskClass(taskinfo.getTaskclass());
            if (num > 0) {
                msg = "2";
                out.print(msg);
                return;
            }
        }
        msg = kpService.addTaskInfo(taskinfo) + "";
        out.print(msg);
    }

    /**
     * @author wdg
     *  修改任務
     */

    @RequestMapping(value = "/modifyTaskAction")
    public void modifyTaskAction(@RequestBody Map<String, Object> reqMap, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        //傳遞一個目前開票的比例
        PrintWriter out = null;
        try {
            out = response.getWriter();
        }
        catch (IOException e) {
            logger.info(e.getMessage());
        }
        String msg = "0";
        String rowguid = reqMap.get("rowguid") == null ? "" : reqMap.get("rowguid").toString();
        TaskInfo taskinfo = kpService.getTaskInfoByGuid(rowguid);
        taskinfo.setAddtime(new Date());
        taskinfo.setTaskname(reqMap.get("taskname") == null ? "" : reqMap.get("taskname").toString());
        taskinfo.setTaskclass(reqMap.get("taskclass") == null ? "" : reqMap.get("taskclass").toString());
        taskinfo.setCronstr(reqMap.get("cornstr") == null ? "" : reqMap.get("cornstr").toString());
        taskinfo.setRunstatus("1".equals(reqMap.get("runstatus")) ? 1 : 0);
        taskinfo.setRemark(reqMap.get("remark") == null ? "" : reqMap.get("remark").toString());
        if (StrUtil.isNotBlank(taskinfo.getTaskname())) {
            int num = kpService.isExistTaskName(taskinfo.getTaskname(), taskinfo.getRowguid());
            if (num > 0) {
                msg = "1";
                out.print(msg);
                return;
            }
        }
        if (StrUtil.isNotBlank(taskinfo.getTaskclass())) {
            int num = kpService.isExistTaskClass(taskinfo.getTaskclass(), taskinfo.getRowguid());
            if (num > 0) {
                msg = "2";
                out.print(msg);
                return;
            }
        }
        msg = kpService.updateTaskInfo(taskinfo) + "";
        out.print(msg);
    }

    /**
     * @author wdg
     * 删除任務
     */
    @RequestMapping(value = "/delTaskAction")
    public void delTaskAction(@RequestBody Map<String, Object> reqMap, HttpServletResponse response, Model model) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        }
        catch (IOException e) {
            logger.info(e.getMessage());
        }
        String rowguid = reqMap.get("rowguid") + "";
        int num = kpService.delTaskByGuid(rowguid);
        out.print(num);
    }

    /**
     * @author wdg
     *  啟動停止任務
     */

    @RequestMapping(value = "/triggerTaskAction")
    public void triggerTaskAction(@RequestBody Map<String, Object> reqMap, HttpServletResponse response, Model model) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        }
        catch (IOException e) {
            logger.info(e.getMessage());
        }
        String rowguid = reqMap.get("rowguid") + "";
        TaskInfo taskinfo = kpService.getTaskInfoByGuid(rowguid);
        String taskclass = taskinfo.getTaskclass();
        if (taskinfo.getRunstatus() == 0) {
            Class<?> clazz = null;
            try {
                clazz = Class.forName(taskclass);
                HashMap<String, Object> hmap = new HashMap<String, Object>();
                hmap.put(ZpBillService.class.getName(), zpBillServiceImpl);
                hmap.put(IKpTimeService.class.getName(), kpService);
                hmap.put(PzService.class.getName(), pzServiceImpl);
                Constructor<?> con = clazz.getConstructor(Map.class);
                future = threadPoolTaskScheduler.schedule((Runnable) con.newInstance(hmap),
                        new CronTrigger(taskinfo.getCronstr()));
                map.put(taskclass, future);
                taskinfo.setRunstatus(1);
                kpService.updateTaskInfo(taskinfo);
                out.print("啟動成功!");
            }
            catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (ClassNotFoundException e) {
                out.print("啟動失敗ClassNotFound:" + e.getMessage());
                e.printStackTrace();
            }
        }
        else {
            try {
                future = map.get(taskclass);
                while (!future.isCancelled()) {
                    future.cancel(true);
                }
                if (future.isCancelled()) {
                    taskinfo.setRunstatus(0);
                    kpService.updateTaskInfo(taskinfo);
                    out.println("暫停成功");
                }
            }
            catch (NullPointerException e) {
                taskinfo.setRunstatus(0);
                kpService.updateTaskInfo(taskinfo);
            }
        }

    }

    @RequestMapping("/stopCron")
    public void stopCron(HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        }
        catch (IOException e) {
            logger.info(e.getMessage());
        }
        threadPoolTaskScheduler.getScheduledExecutor().shutdown();
        threadPoolTaskScheduler.destroy();
        threadPoolTaskScheduler.initialize();
        if (map.size() > 0) {
            map.clear();
        }
        List<TaskInfo> list = kpService.getTaskInfoList();
        for (TaskInfo taskinfo : list) {
            if (taskinfo.getRunstatus() == 1) {
                taskinfo.setRunstatus(0);
                kpService.updateTaskInfo(taskinfo);
            }
        }
        out.print("全部服務關閉");
    }
}      
package com.hangxin.time.job;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Element;

import com.hangxin.commons.util.PageModel;
import com.hangxin.system.util.GlobalUtil;
import com.hangxin.time.service.IKpTimeService;
import com.hangxin.xxdzfp.service.PzService;
import com.hangxin.xxdzfp.service.ZpBillService;
import com.hangxin.xxdzfp.util.Ikp;
import com.hangxin.xxdzfp.util.KpNeg;
import com.hangxin.xxdzfp.util.KpPos;

public class KPRunnable implements Runnable
{

    private Logger logger;

    private LinkedList<Map<String, Object>> linkedList = null;

    private int wknum = 0;

    private ZpBillService zpBillServiceImpl;
    private IKpTimeService kpService;
    private PzService pzServiceImpl;

    public KPRunnable(Map<String, Object> conmap) {
        logger = Logger.getLogger(KPRunnable.class);
        zpBillServiceImpl = (ZpBillService) conmap.get(ZpBillService.class.getName());
        kpService = (IKpTimeService) conmap.get(IKpTimeService.class.getName());
        pzServiceImpl = (PzService) conmap.get(PzService.class.getName());
        wknum = kpService.getNoKpNum();
        if (wknum != 0) {
            String taxno = GlobalUtil.getProperty("taxno");
            PageModel<Map<String, Object>> pageModel = new PageModel<Map<String, Object>>();
            pageModel.setPages(1);
            pageModel.setPageNo(1);
            pageModel.setPageSize(wknum);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("invoicetype", "1");
            map.put("nsrsbh", taxno);
            pageModel = zpBillServiceImpl.findXxfpList(pageModel, map);
            List<Map<String, Object>> list = pageModel.getList();
            linkedList = new LinkedList<Map<String, Object>>(list);
        }

    }

    @Override
    public void run() {

        System.out.println("開票服務正在進行......");
        if (linkedList != null) {
            Map<String, Object> linkmap = linkedList.getFirst();
            try {
                String data = "";
                Ikp ikp = null;
                if (!"".equals(linkmap.get("YFP_DM").toString())) {
                    ikp = new KpNeg();
                }
                else {
                    ikp = new KpPos();
                }
                Element res = zpBillServiceImpl.kp(Long.valueOf(Long.parseLong(linkmap.get("id").toString())), ikp);
                if ("0000".equals(res.element("RETURNCODE").getText())) {
                    zpBillServiceImpl.backResult(res, Long.valueOf(Long.parseLong(linkmap.get("id").toString())));
                    logger.info("NSRDZDAH:" + linkmap.get("NSRDZDAH") + "開票成功!");
                    linkedList.removeFirst();
                }
                else {
                    data = res.element("RETURNCODE").getText() + ":" + res.element("RETURNMSG").getText();
                    logger.debug(linkmap.get("id").toString() + ":" + data);
                    logger.info("NSRDZDAH:" + linkmap.get("NSRDZDAH") + "開票失敗:" + data);
                    linkedList.removeFirst();
                }

            }
            catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

}