实现的效果:
类似这样的一个定时管理,对程序的中定时计划可以动态的控制其运行还是关闭
第一步:创建数据表:
如上图所示,创建如此数据表即可,而且关键的是最后的两个字段还没有用到
第二步,页面:
就是上面的三个页面,一个添加,一个修改,一个列表页面
第三步:后台代码的实现:
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("全部服务关闭");
}
}
然后是Runnable:
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();
}
}
}
}
上面就是主要的代码了,希望对你有所帮助!