update xxl-job 2.3.0 => 2.3.1

2.X
疯狂的狮子Li 2022-05-22 13:17:53 +08:00
parent b3b763b88c
commit 3646b9b7f0
64 changed files with 2512 additions and 2479 deletions

View File

@ -33,7 +33,7 @@
<hutool.version>5.8.1</hutool.version> <hutool.version>5.8.1</hutool.version>
<redisson.version>3.17.0</redisson.version> <redisson.version>3.17.0</redisson.version>
<lock4j.version>2.2.1</lock4j.version> <lock4j.version>2.2.1</lock4j.version>
<xxl-job.version>2.3.0</xxl-job.version> <xxl-job.version>2.3.1</xxl-job.version>
<knife4j-aggregation.version>2.0.9</knife4j-aggregation.version> <knife4j-aggregation.version>2.0.9</knife4j-aggregation.version>
<knife4j.version>3.0.3</knife4j.version> <knife4j.version>3.0.3</knife4j.version>
<satoken.version>1.30.0</satoken.version> <satoken.version>1.30.0</satoken.version>

View File

@ -9,8 +9,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class XxlJobAdminApplication { public class XxlJobAdminApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(XxlJobAdminApplication.class, args); SpringApplication.run(XxlJobAdminApplication.class, args);
} }
} }

View File

@ -24,73 +24,74 @@ import java.util.Map;
/** /**
* index controller * index controller
*
* @author xuxueli 2015-12-19 16:13:16 * @author xuxueli 2015-12-19 16:13:16
*/ */
@Controller @Controller
public class IndexController { public class IndexController {
@Resource @Resource
private XxlJobService xxlJobService; private XxlJobService xxlJobService;
@Resource @Resource
private LoginService loginService; private LoginService loginService;
@RequestMapping("/") @RequestMapping("/")
public String index(Model model) { public String index(Model model) {
Map<String, Object> dashboardMap = xxlJobService.dashboardInfo(); Map<String, Object> dashboardMap = xxlJobService.dashboardInfo();
model.addAllAttributes(dashboardMap); model.addAllAttributes(dashboardMap);
return "index"; return "index";
} }
@RequestMapping("/chartInfo") @RequestMapping("/chartInfo")
@ResponseBody @ResponseBody
public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) { public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) {
ReturnT<Map<String, Object>> chartInfo = xxlJobService.chartInfo(startDate, endDate); ReturnT<Map<String, Object>> chartInfo = xxlJobService.chartInfo(startDate, endDate);
return chartInfo; return chartInfo;
} }
@RequestMapping("/toLogin") @RequestMapping("/toLogin")
@PermissionLimit(limit=false) @PermissionLimit(limit = false)
public ModelAndView toLogin(HttpServletRequest request, HttpServletResponse response,ModelAndView modelAndView) { public ModelAndView toLogin(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) {
if (loginService.ifLogin(request, response) != null) { if (loginService.ifLogin(request, response) != null) {
modelAndView.setView(new RedirectView("/",true,false)); modelAndView.setView(new RedirectView("/", true, false));
return modelAndView; return modelAndView;
} }
return new ModelAndView("login"); return new ModelAndView("login");
} }
@RequestMapping(value="login", method=RequestMethod.POST) @RequestMapping(value = "login", method = RequestMethod.POST)
@ResponseBody @ResponseBody
@PermissionLimit(limit=false) @PermissionLimit(limit = false)
public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){ public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember) {
boolean ifRem = (ifRemember!=null && ifRemember.trim().length()>0 && "on".equals(ifRemember))?true:false; boolean ifRem = (ifRemember != null && ifRemember.trim().length() > 0 && "on".equals(ifRemember)) ? true : false;
return loginService.login(request, response, userName, password, ifRem); return loginService.login(request, response, userName, password, ifRem);
} }
@RequestMapping(value="logout", method=RequestMethod.POST) @RequestMapping(value = "logout", method = RequestMethod.POST)
@ResponseBody @ResponseBody
@PermissionLimit(limit=false) @PermissionLimit(limit = false)
public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){ public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response) {
return loginService.logout(request, response); return loginService.logout(request, response);
} }
@RequestMapping("/help") @RequestMapping("/help")
public String help() { public String help() {
/*if (!PermissionInterceptor.ifLogin(request)) { /*if (!PermissionInterceptor.ifLogin(request)) {
return "redirect:/toLogin"; return "redirect:/toLogin";
}*/ }*/
return "help"; return "help";
} }
@InitBinder @InitBinder
public void initBinder(WebDataBinder binder) { public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false); dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
} }
} }

View File

@ -37,19 +37,19 @@ public class JobApiController {
*/ */
@RequestMapping("/{uri}") @RequestMapping("/{uri}")
@ResponseBody @ResponseBody
@PermissionLimit(limit=false) @PermissionLimit(limit = false)
public ReturnT<String> api(HttpServletRequest request, @PathVariable("uri") String uri, @RequestBody(required = false) String data) { public ReturnT<String> api(HttpServletRequest request, @PathVariable("uri") String uri, @RequestBody(required = false) String data) {
// valid // valid
if (!"POST".equalsIgnoreCase(request.getMethod())) { if (!"POST".equalsIgnoreCase(request.getMethod())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, HttpMethod not support."); return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, HttpMethod not support.");
} }
if (uri==null || uri.trim().length()==0) { if (uri == null || uri.trim().length() == 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping empty."); return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping empty.");
} }
if (XxlJobAdminConfig.getAdminConfig().getAccessToken()!=null if (XxlJobAdminConfig.getAdminConfig().getAccessToken() != null
&& XxlJobAdminConfig.getAdminConfig().getAccessToken().trim().length()>0 && XxlJobAdminConfig.getAdminConfig().getAccessToken().trim().length() > 0
&& !XxlJobAdminConfig.getAdminConfig().getAccessToken().equals(request.getHeader(XxlJobRemotingUtil.XXL_JOB_ACCESS_TOKEN))) { && !XxlJobAdminConfig.getAdminConfig().getAccessToken().equals(request.getHeader(XxlJobRemotingUtil.XXL_JOB_ACCESS_TOKEN))) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "The access token is wrong."); return new ReturnT<String>(ReturnT.FAIL_CODE, "The access token is wrong.");
} }
@ -64,7 +64,7 @@ public class JobApiController {
RegistryParam registryParam = GsonTool.fromJson(data, RegistryParam.class); RegistryParam registryParam = GsonTool.fromJson(data, RegistryParam.class);
return adminBiz.registryRemove(registryParam); return adminBiz.registryRemove(registryParam);
} else { } else {
return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping("+ uri +") not found."); return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping(" + uri + ") not found.");
} }
} }

View File

@ -19,78 +19,79 @@ import java.util.List;
/** /**
* job code controller * job code controller
*
* @author xuxueli 2015-12-19 16:13:16 * @author xuxueli 2015-12-19 16:13:16
*/ */
@Controller @Controller
@RequestMapping("/jobcode") @RequestMapping("/jobcode")
public class JobCodeController { public class JobCodeController {
@Resource @Resource
private XxlJobInfoDao xxlJobInfoDao; private XxlJobInfoDao xxlJobInfoDao;
@Resource @Resource
private XxlJobLogGlueDao xxlJobLogGlueDao; private XxlJobLogGlueDao xxlJobLogGlueDao;
@RequestMapping @RequestMapping
public String index(HttpServletRequest request, Model model, int jobId) { public String index(HttpServletRequest request, Model model, int jobId) {
XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId); XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId);
List<XxlJobLogGlue> jobLogGlues = xxlJobLogGlueDao.findByJobId(jobId); List<XxlJobLogGlue> jobLogGlues = xxlJobLogGlueDao.findByJobId(jobId);
if (jobInfo == null) { if (jobInfo == null) {
throw new RuntimeException(I18nUtil.getString("jobinfo_glue_jobid_unvalid")); throw new RuntimeException(I18nUtil.getString("jobinfo_glue_jobid_unvalid"));
} }
if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType())) { if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType())) {
throw new RuntimeException(I18nUtil.getString("jobinfo_glue_gluetype_unvalid")); throw new RuntimeException(I18nUtil.getString("jobinfo_glue_gluetype_unvalid"));
} }
// valid permission // valid permission
JobInfoController.validPermission(request, jobInfo.getJobGroup()); JobInfoController.validPermission(request, jobInfo.getJobGroup());
// Glue类型-字典 // Glue类型-字典
model.addAttribute("GlueTypeEnum", GlueTypeEnum.values()); model.addAttribute("GlueTypeEnum", GlueTypeEnum.values());
model.addAttribute("jobInfo", jobInfo); model.addAttribute("jobInfo", jobInfo);
model.addAttribute("jobLogGlues", jobLogGlues); model.addAttribute("jobLogGlues", jobLogGlues);
return "jobcode/jobcode.index"; return "jobcode/jobcode.index";
} }
@RequestMapping("/save") @RequestMapping("/save")
@ResponseBody @ResponseBody
public ReturnT<String> save(Model model, int id, String glueSource, String glueRemark) { public ReturnT<String> save(Model model, int id, String glueSource, String glueRemark) {
// valid // valid
if (glueRemark==null) { if (glueRemark == null) {
return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_glue_remark")) ); return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_glue_remark")));
} }
if (glueRemark.length()<4 || glueRemark.length()>100) { if (glueRemark.length() < 4 || glueRemark.length() > 100) {
return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_remark_limit")); return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_remark_limit"));
} }
XxlJobInfo exists_jobInfo = xxlJobInfoDao.loadById(id); XxlJobInfo exists_jobInfo = xxlJobInfoDao.loadById(id);
if (exists_jobInfo == null) { if (exists_jobInfo == null) {
return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_jobid_unvalid")); return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_jobid_unvalid"));
} }
// update new code // update new code
exists_jobInfo.setGlueSource(glueSource); exists_jobInfo.setGlueSource(glueSource);
exists_jobInfo.setGlueRemark(glueRemark); exists_jobInfo.setGlueRemark(glueRemark);
exists_jobInfo.setGlueUpdatetime(new Date()); exists_jobInfo.setGlueUpdatetime(new Date());
exists_jobInfo.setUpdateTime(new Date()); exists_jobInfo.setUpdateTime(new Date());
xxlJobInfoDao.update(exists_jobInfo); xxlJobInfoDao.update(exists_jobInfo);
// log old code // log old code
XxlJobLogGlue xxlJobLogGlue = new XxlJobLogGlue(); XxlJobLogGlue xxlJobLogGlue = new XxlJobLogGlue();
xxlJobLogGlue.setJobId(exists_jobInfo.getId()); xxlJobLogGlue.setJobId(exists_jobInfo.getId());
xxlJobLogGlue.setGlueType(exists_jobInfo.getGlueType()); xxlJobLogGlue.setGlueType(exists_jobInfo.getGlueType());
xxlJobLogGlue.setGlueSource(glueSource); xxlJobLogGlue.setGlueSource(glueSource);
xxlJobLogGlue.setGlueRemark(glueRemark); xxlJobLogGlue.setGlueRemark(glueRemark);
xxlJobLogGlue.setAddTime(new Date()); xxlJobLogGlue.setAddTime(new Date());
xxlJobLogGlue.setUpdateTime(new Date()); xxlJobLogGlue.setUpdateTime(new Date());
xxlJobLogGlueDao.save(xxlJobLogGlue); xxlJobLogGlueDao.save(xxlJobLogGlue);
// remove code backup more than 30 // remove code backup more than 30
xxlJobLogGlueDao.removeOld(exists_jobInfo.getId(), 30); xxlJobLogGlueDao.removeOld(exists_jobInfo.getId(), 30);
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
} }

View File

@ -20,178 +20,179 @@ import java.util.*;
/** /**
* job group controller * job group controller
*
* @author xuxueli 2016-10-02 20:52:56 * @author xuxueli 2016-10-02 20:52:56
*/ */
@Controller @Controller
@RequestMapping("/jobgroup") @RequestMapping("/jobgroup")
public class JobGroupController { public class JobGroupController {
@Resource @Resource
public XxlJobInfoDao xxlJobInfoDao; public XxlJobInfoDao xxlJobInfoDao;
@Resource @Resource
public XxlJobGroupDao xxlJobGroupDao; public XxlJobGroupDao xxlJobGroupDao;
@Resource @Resource
private XxlJobRegistryDao xxlJobRegistryDao; private XxlJobRegistryDao xxlJobRegistryDao;
@RequestMapping @RequestMapping
public String index(Model model) { public String index(Model model) {
return "jobgroup/jobgroup.index"; return "jobgroup/jobgroup.index";
} }
@RequestMapping("/pageList") @RequestMapping("/pageList")
@ResponseBody @ResponseBody
public Map<String, Object> pageList(HttpServletRequest request, public Map<String, Object> pageList(HttpServletRequest request,
@RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "0") int start,
@RequestParam(required = false, defaultValue = "10") int length, @RequestParam(required = false, defaultValue = "10") int length,
String appname, String title) { String appname, String title) {
// page query // page query
List<XxlJobGroup> list = xxlJobGroupDao.pageList(start, length, appname, title); List<XxlJobGroup> list = xxlJobGroupDao.pageList(start, length, appname, title);
int list_count = xxlJobGroupDao.pageListCount(start, length, appname, title); int list_count = xxlJobGroupDao.pageListCount(start, length, appname, title);
// package result // package result
Map<String, Object> maps = new HashMap<String, Object>(); Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数 maps.put("recordsTotal", list_count); // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数 maps.put("recordsFiltered", list_count); // 过滤后的总记录数
maps.put("data", list); // 分页列表 maps.put("data", list); // 分页列表
return maps; return maps;
} }
@RequestMapping("/save") @RequestMapping("/save")
@ResponseBody @ResponseBody
public ReturnT<String> save(XxlJobGroup xxlJobGroup){ public ReturnT<String> save(XxlJobGroup xxlJobGroup) {
// valid // valid
if (xxlJobGroup.getAppname()==null || xxlJobGroup.getAppname().trim().length()==0) { if (xxlJobGroup.getAppname() == null || xxlJobGroup.getAppname().trim().length() == 0) {
return new ReturnT<String>(500, (I18nUtil.getString("system_please_input")+"AppName") ); return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + "AppName"));
} }
if (xxlJobGroup.getAppname().length()<4 || xxlJobGroup.getAppname().length()>64) { if (xxlJobGroup.getAppname().length() < 4 || xxlJobGroup.getAppname().length() > 64) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_appname_length") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_appname_length"));
} }
if (xxlJobGroup.getAppname().contains(">") || xxlJobGroup.getAppname().contains("<")) { if (xxlJobGroup.getAppname().contains(">") || xxlJobGroup.getAppname().contains("<")) {
return new ReturnT<String>(500, "AppName"+I18nUtil.getString("system_unvalid") ); return new ReturnT<String>(500, "AppName" + I18nUtil.getString("system_unvalid"));
} }
if (xxlJobGroup.getTitle()==null || xxlJobGroup.getTitle().trim().length()==0) { if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().length() == 0) {
return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")) ); return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
} }
if (xxlJobGroup.getTitle().contains(">") || xxlJobGroup.getTitle().contains("<")) { if (xxlJobGroup.getTitle().contains(">") || xxlJobGroup.getTitle().contains("<")) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_title")+I18nUtil.getString("system_unvalid") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_title") + I18nUtil.getString("system_unvalid"));
} }
if (xxlJobGroup.getAddressType()!=0) { if (xxlJobGroup.getAddressType() != 0) {
if (xxlJobGroup.getAddressList()==null || xxlJobGroup.getAddressList().trim().length()==0) { if (xxlJobGroup.getAddressList() == null || xxlJobGroup.getAddressList().trim().length() == 0) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_addressType_limit") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_addressType_limit"));
} }
if (xxlJobGroup.getAddressList().contains(">") || xxlJobGroup.getAddressList().contains("<")) { if (xxlJobGroup.getAddressList().contains(">") || xxlJobGroup.getAddressList().contains("<")) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList")+I18nUtil.getString("system_unvalid") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList") + I18nUtil.getString("system_unvalid"));
} }
String[] addresss = xxlJobGroup.getAddressList().split(","); String[] addresss = xxlJobGroup.getAddressList().split(",");
for (String item: addresss) { for (String item : addresss) {
if (item==null || item.trim().length()==0) { if (item == null || item.trim().length() == 0) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList_unvalid") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList_unvalid"));
} }
} }
} }
// process // process
xxlJobGroup.setUpdateTime(new Date()); xxlJobGroup.setUpdateTime(new Date());
int ret = xxlJobGroupDao.save(xxlJobGroup); int ret = xxlJobGroupDao.save(xxlJobGroup);
return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL; return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
} }
@RequestMapping("/update") @RequestMapping("/update")
@ResponseBody @ResponseBody
public ReturnT<String> update(XxlJobGroup xxlJobGroup){ public ReturnT<String> update(XxlJobGroup xxlJobGroup) {
// valid // valid
if (xxlJobGroup.getAppname()==null || xxlJobGroup.getAppname().trim().length()==0) { if (xxlJobGroup.getAppname() == null || xxlJobGroup.getAppname().trim().length() == 0) {
return new ReturnT<String>(500, (I18nUtil.getString("system_please_input")+"AppName") ); return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + "AppName"));
} }
if (xxlJobGroup.getAppname().length()<4 || xxlJobGroup.getAppname().length()>64) { if (xxlJobGroup.getAppname().length() < 4 || xxlJobGroup.getAppname().length() > 64) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_appname_length") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_appname_length"));
} }
if (xxlJobGroup.getTitle()==null || xxlJobGroup.getTitle().trim().length()==0) { if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().length() == 0) {
return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")) ); return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
} }
if (xxlJobGroup.getAddressType() == 0) { if (xxlJobGroup.getAddressType() == 0) {
// 0=自动注册 // 0=自动注册
List<String> registryList = findRegistryByAppName(xxlJobGroup.getAppname()); List<String> registryList = findRegistryByAppName(xxlJobGroup.getAppname());
String addressListStr = null; String addressListStr = null;
if (registryList!=null && !registryList.isEmpty()) { if (registryList != null && !registryList.isEmpty()) {
Collections.sort(registryList); Collections.sort(registryList);
addressListStr = ""; addressListStr = "";
for (String item:registryList) { for (String item : registryList) {
addressListStr += item + ","; addressListStr += item + ",";
} }
addressListStr = addressListStr.substring(0, addressListStr.length()-1); addressListStr = addressListStr.substring(0, addressListStr.length() - 1);
} }
xxlJobGroup.setAddressList(addressListStr); xxlJobGroup.setAddressList(addressListStr);
} else { } else {
// 1=手动录入 // 1=手动录入
if (xxlJobGroup.getAddressList()==null || xxlJobGroup.getAddressList().trim().length()==0) { if (xxlJobGroup.getAddressList() == null || xxlJobGroup.getAddressList().trim().length() == 0) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_addressType_limit") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_addressType_limit"));
} }
String[] addresss = xxlJobGroup.getAddressList().split(","); String[] addresss = xxlJobGroup.getAddressList().split(",");
for (String item: addresss) { for (String item : addresss) {
if (item==null || item.trim().length()==0) { if (item == null || item.trim().length() == 0) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList_unvalid") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList_unvalid"));
} }
} }
} }
// process // process
xxlJobGroup.setUpdateTime(new Date()); xxlJobGroup.setUpdateTime(new Date());
int ret = xxlJobGroupDao.update(xxlJobGroup); int ret = xxlJobGroupDao.update(xxlJobGroup);
return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL; return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
} }
private List<String> findRegistryByAppName(String appnameParam){ private List<String> findRegistryByAppName(String appnameParam) {
HashMap<String, List<String>> appAddressMap = new HashMap<String, List<String>>(); HashMap<String, List<String>> appAddressMap = new HashMap<String, List<String>>();
List<XxlJobRegistry> list = xxlJobRegistryDao.findAll(RegistryConfig.DEAD_TIMEOUT, new Date()); List<XxlJobRegistry> list = xxlJobRegistryDao.findAll(RegistryConfig.DEAD_TIMEOUT, new Date());
if (list != null) { if (list != null) {
for (XxlJobRegistry item: list) { for (XxlJobRegistry item : list) {
if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) { if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) {
String appname = item.getRegistryKey(); String appname = item.getRegistryKey();
List<String> registryList = appAddressMap.get(appname); List<String> registryList = appAddressMap.get(appname);
if (registryList == null) { if (registryList == null) {
registryList = new ArrayList<String>(); registryList = new ArrayList<String>();
} }
if (!registryList.contains(item.getRegistryValue())) { if (!registryList.contains(item.getRegistryValue())) {
registryList.add(item.getRegistryValue()); registryList.add(item.getRegistryValue());
} }
appAddressMap.put(appname, registryList); appAddressMap.put(appname, registryList);
} }
} }
} }
return appAddressMap.get(appnameParam); return appAddressMap.get(appnameParam);
} }
@RequestMapping("/remove") @RequestMapping("/remove")
@ResponseBody @ResponseBody
public ReturnT<String> remove(int id){ public ReturnT<String> remove(int id) {
// valid // valid
int count = xxlJobInfoDao.pageListCount(0, 10, id, -1, null, null, null); int count = xxlJobInfoDao.pageListCount(0, 10, id, -1, null, null, null);
if (count > 0) { if (count > 0) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_del_limit_0") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_del_limit_0"));
} }
List<XxlJobGroup> allList = xxlJobGroupDao.findAll(); List<XxlJobGroup> allList = xxlJobGroupDao.findAll();
if (allList.size() == 1) { if (allList.size() == 1) {
return new ReturnT<String>(500, I18nUtil.getString("jobgroup_del_limit_1") ); return new ReturnT<String>(500, I18nUtil.getString("jobgroup_del_limit_1"));
} }
int ret = xxlJobGroupDao.remove(id); int ret = xxlJobGroupDao.remove(id);
return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL; return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
} }
@RequestMapping("/loadById") @RequestMapping("/loadById")
@ResponseBody @ResponseBody
public ReturnT<XxlJobGroup> loadById(int id){ public ReturnT<XxlJobGroup> loadById(int id) {
XxlJobGroup jobGroup = xxlJobGroupDao.load(id); XxlJobGroup jobGroup = xxlJobGroupDao.load(id);
return jobGroup!=null?new ReturnT<XxlJobGroup>(jobGroup):new ReturnT<XxlJobGroup>(ReturnT.FAIL_CODE, null); return jobGroup != null ? new ReturnT<XxlJobGroup>(jobGroup) : new ReturnT<XxlJobGroup>(ReturnT.FAIL_CODE, null);
} }
} }

View File

@ -1,6 +1,5 @@
package com.xxl.job.admin.controller; package com.xxl.job.admin.controller;
import com.xxl.job.admin.core.cron.CronExpression;
import com.xxl.job.admin.core.exception.XxlJobException; import com.xxl.job.admin.core.exception.XxlJobException;
import com.xxl.job.admin.core.model.XxlJobGroup; import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo; import com.xxl.job.admin.core.model.XxlJobInfo;
@ -29,152 +28,153 @@ import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*; import java.util.*;
/** /**
* index controller * index controller
*
* @author xuxueli 2015-12-19 16:13:16 * @author xuxueli 2015-12-19 16:13:16
*/ */
@Controller @Controller
@RequestMapping("/jobinfo") @RequestMapping("/jobinfo")
public class JobInfoController { public class JobInfoController {
private static Logger logger = LoggerFactory.getLogger(JobInfoController.class); private static Logger logger = LoggerFactory.getLogger(JobInfoController.class);
@Resource @Resource
private XxlJobGroupDao xxlJobGroupDao; private XxlJobGroupDao xxlJobGroupDao;
@Resource @Resource
private XxlJobService xxlJobService; private XxlJobService xxlJobService;
@RequestMapping @RequestMapping
public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "-1") int jobGroup) { public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "-1") int jobGroup) {
// 枚举-字典 // 枚举-字典
model.addAttribute("ExecutorRouteStrategyEnum", ExecutorRouteStrategyEnum.values()); // 路由策略-列表 model.addAttribute("ExecutorRouteStrategyEnum", ExecutorRouteStrategyEnum.values()); // 路由策略-列表
model.addAttribute("GlueTypeEnum", GlueTypeEnum.values()); // Glue类型-字典 model.addAttribute("GlueTypeEnum", GlueTypeEnum.values()); // Glue类型-字典
model.addAttribute("ExecutorBlockStrategyEnum", ExecutorBlockStrategyEnum.values()); // 阻塞处理策略-字典 model.addAttribute("ExecutorBlockStrategyEnum", ExecutorBlockStrategyEnum.values()); // 阻塞处理策略-字典
model.addAttribute("ScheduleTypeEnum", ScheduleTypeEnum.values()); // 调度类型 model.addAttribute("ScheduleTypeEnum", ScheduleTypeEnum.values()); // 调度类型
model.addAttribute("MisfireStrategyEnum", MisfireStrategyEnum.values()); // 调度过期策略 model.addAttribute("MisfireStrategyEnum", MisfireStrategyEnum.values()); // 调度过期策略
// 执行器列表 // 执行器列表
List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll(); List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll();
// filter group // filter group
List<XxlJobGroup> jobGroupList = filterJobGroupByRole(request, jobGroupList_all); List<XxlJobGroup> jobGroupList = filterJobGroupByRole(request, jobGroupList_all);
if (jobGroupList==null || jobGroupList.size()==0) { if (jobGroupList == null || jobGroupList.size() == 0) {
throw new XxlJobException(I18nUtil.getString("jobgroup_empty")); throw new XxlJobException(I18nUtil.getString("jobgroup_empty"));
} }
model.addAttribute("JobGroupList", jobGroupList); model.addAttribute("JobGroupList", jobGroupList);
model.addAttribute("jobGroup", jobGroup); model.addAttribute("jobGroup", jobGroup);
return "jobinfo/jobinfo.index"; return "jobinfo/jobinfo.index";
} }
public static List<XxlJobGroup> filterJobGroupByRole(HttpServletRequest request, List<XxlJobGroup> jobGroupList_all){ public static List<XxlJobGroup> filterJobGroupByRole(HttpServletRequest request, List<XxlJobGroup> jobGroupList_all) {
List<XxlJobGroup> jobGroupList = new ArrayList<>(); List<XxlJobGroup> jobGroupList = new ArrayList<>();
if (jobGroupList_all!=null && jobGroupList_all.size()>0) { if (jobGroupList_all != null && jobGroupList_all.size() > 0) {
XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY); XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
if (loginUser.getRole() == 1) { if (loginUser.getRole() == 1) {
jobGroupList = jobGroupList_all; jobGroupList = jobGroupList_all;
} else { } else {
List<String> groupIdStrs = new ArrayList<>(); List<String> groupIdStrs = new ArrayList<>();
if (loginUser.getPermission()!=null && loginUser.getPermission().trim().length()>0) { if (loginUser.getPermission() != null && loginUser.getPermission().trim().length() > 0) {
groupIdStrs = Arrays.asList(loginUser.getPermission().trim().split(",")); groupIdStrs = Arrays.asList(loginUser.getPermission().trim().split(","));
} }
for (XxlJobGroup groupItem:jobGroupList_all) { for (XxlJobGroup groupItem : jobGroupList_all) {
if (groupIdStrs.contains(String.valueOf(groupItem.getId()))) { if (groupIdStrs.contains(String.valueOf(groupItem.getId()))) {
jobGroupList.add(groupItem); jobGroupList.add(groupItem);
} }
} }
} }
} }
return jobGroupList; return jobGroupList;
} }
public static void validPermission(HttpServletRequest request, int jobGroup) {
XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
if (!loginUser.validPermission(jobGroup)) {
throw new RuntimeException(I18nUtil.getString("system_permission_limit") + "[username="+ loginUser.getUsername() +"]");
}
}
@RequestMapping("/pageList") public static void validPermission(HttpServletRequest request, int jobGroup) {
@ResponseBody XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start, if (!loginUser.validPermission(jobGroup)) {
@RequestParam(required = false, defaultValue = "10") int length, throw new RuntimeException(I18nUtil.getString("system_permission_limit") + "[username=" + loginUser.getUsername() + "]");
int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) { }
}
return xxlJobService.pageList(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author); @RequestMapping("/pageList")
} @ResponseBody
public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,
@RequestParam(required = false, defaultValue = "10") int length,
int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) {
@RequestMapping("/add") return xxlJobService.pageList(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author);
@ResponseBody }
public ReturnT<String> add(XxlJobInfo jobInfo) {
return xxlJobService.add(jobInfo);
}
@RequestMapping("/update") @RequestMapping("/add")
@ResponseBody @ResponseBody
public ReturnT<String> update(XxlJobInfo jobInfo) { public ReturnT<String> add(XxlJobInfo jobInfo) {
return xxlJobService.update(jobInfo); return xxlJobService.add(jobInfo);
} }
@RequestMapping("/remove") @RequestMapping("/update")
@ResponseBody @ResponseBody
public ReturnT<String> remove(int id) { public ReturnT<String> update(XxlJobInfo jobInfo) {
return xxlJobService.remove(id); return xxlJobService.update(jobInfo);
} }
@RequestMapping("/stop") @RequestMapping("/remove")
@ResponseBody @ResponseBody
public ReturnT<String> pause(int id) { public ReturnT<String> remove(int id) {
return xxlJobService.stop(id); return xxlJobService.remove(id);
} }
@RequestMapping("/start") @RequestMapping("/stop")
@ResponseBody @ResponseBody
public ReturnT<String> start(int id) { public ReturnT<String> pause(int id) {
return xxlJobService.start(id); return xxlJobService.stop(id);
} }
@RequestMapping("/trigger") @RequestMapping("/start")
@ResponseBody @ResponseBody
//@PermissionLimit(limit = false) public ReturnT<String> start(int id) {
public ReturnT<String> triggerJob(int id, String executorParam, String addressList) { return xxlJobService.start(id);
// force cover job param }
if (executorParam == null) {
executorParam = "";
}
JobTriggerPoolHelper.trigger(id, TriggerTypeEnum.MANUAL, -1, null, executorParam, addressList); @RequestMapping("/trigger")
return ReturnT.SUCCESS; @ResponseBody
} //@PermissionLimit(limit = false)
public ReturnT<String> triggerJob(int id, String executorParam, String addressList) {
// force cover job param
if (executorParam == null) {
executorParam = "";
}
@RequestMapping("/nextTriggerTime") JobTriggerPoolHelper.trigger(id, TriggerTypeEnum.MANUAL, -1, null, executorParam, addressList);
@ResponseBody return ReturnT.SUCCESS;
public ReturnT<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) { }
XxlJobInfo paramXxlJobInfo = new XxlJobInfo(); @RequestMapping("/nextTriggerTime")
paramXxlJobInfo.setScheduleType(scheduleType); @ResponseBody
paramXxlJobInfo.setScheduleConf(scheduleConf); public ReturnT<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) {
List<String> result = new ArrayList<>(); XxlJobInfo paramXxlJobInfo = new XxlJobInfo();
try { paramXxlJobInfo.setScheduleType(scheduleType);
Date lastTime = new Date(); paramXxlJobInfo.setScheduleConf(scheduleConf);
for (int i = 0; i < 5; i++) {
lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
if (lastTime != null) {
result.add(DateUtil.formatDateTime(lastTime));
} else {
break;
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) + e.getMessage());
}
return new ReturnT<List<String>>(result);
} List<String> result = new ArrayList<>();
try {
Date lastTime = new Date();
for (int i = 0; i < 5; i++) {
lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
if (lastTime != null) {
result.add(DateUtil.formatDateTime(lastTime));
} else {
break;
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")) + e.getMessage());
}
return new ReturnT<List<String>>(result);
}
} }

View File

@ -1,7 +1,7 @@
package com.xxl.job.admin.controller; package com.xxl.job.admin.controller;
import com.xxl.job.admin.core.exception.XxlJobException;
import com.xxl.job.admin.core.complete.XxlJobCompleter; import com.xxl.job.admin.core.complete.XxlJobCompleter;
import com.xxl.job.admin.core.exception.XxlJobException;
import com.xxl.job.admin.core.model.XxlJobGroup; import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo; import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog; import com.xxl.job.admin.core.model.XxlJobLog;
@ -33,201 +33,202 @@ import java.util.Map;
/** /**
* index controller * index controller
*
* @author xuxueli 2015-12-19 16:13:16 * @author xuxueli 2015-12-19 16:13:16
*/ */
@Controller @Controller
@RequestMapping("/joblog") @RequestMapping("/joblog")
public class JobLogController { public class JobLogController {
private static Logger logger = LoggerFactory.getLogger(JobLogController.class); private static Logger logger = LoggerFactory.getLogger(JobLogController.class);
@Resource @Resource
private XxlJobGroupDao xxlJobGroupDao; private XxlJobGroupDao xxlJobGroupDao;
@Resource @Resource
public XxlJobInfoDao xxlJobInfoDao; public XxlJobInfoDao xxlJobInfoDao;
@Resource @Resource
public XxlJobLogDao xxlJobLogDao; public XxlJobLogDao xxlJobLogDao;
@RequestMapping @RequestMapping
public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "0") Integer jobId) { public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "0") Integer jobId) {
// 执行器列表 // 执行器列表
List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll(); List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll();
// filter group // filter group
List<XxlJobGroup> jobGroupList = JobInfoController.filterJobGroupByRole(request, jobGroupList_all); List<XxlJobGroup> jobGroupList = JobInfoController.filterJobGroupByRole(request, jobGroupList_all);
if (jobGroupList==null || jobGroupList.size()==0) { if (jobGroupList == null || jobGroupList.size() == 0) {
throw new XxlJobException(I18nUtil.getString("jobgroup_empty")); throw new XxlJobException(I18nUtil.getString("jobgroup_empty"));
} }
model.addAttribute("JobGroupList", jobGroupList); model.addAttribute("JobGroupList", jobGroupList);
// 任务 // 任务
if (jobId > 0) { if (jobId > 0) {
XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId); XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId);
if (jobInfo == null) { if (jobInfo == null) {
throw new RuntimeException(I18nUtil.getString("jobinfo_field_id") + I18nUtil.getString("system_unvalid")); throw new RuntimeException(I18nUtil.getString("jobinfo_field_id") + I18nUtil.getString("system_unvalid"));
} }
model.addAttribute("jobInfo", jobInfo); model.addAttribute("jobInfo", jobInfo);
// valid permission // valid permission
JobInfoController.validPermission(request, jobInfo.getJobGroup()); JobInfoController.validPermission(request, jobInfo.getJobGroup());
} }
return "joblog/joblog.index"; return "joblog/joblog.index";
} }
@RequestMapping("/getJobsByGroup") @RequestMapping("/getJobsByGroup")
@ResponseBody @ResponseBody
public ReturnT<List<XxlJobInfo>> getJobsByGroup(int jobGroup){ public ReturnT<List<XxlJobInfo>> getJobsByGroup(int jobGroup) {
List<XxlJobInfo> list = xxlJobInfoDao.getJobsByGroup(jobGroup); List<XxlJobInfo> list = xxlJobInfoDao.getJobsByGroup(jobGroup);
return new ReturnT<List<XxlJobInfo>>(list); return new ReturnT<List<XxlJobInfo>>(list);
} }
@RequestMapping("/pageList") @RequestMapping("/pageList")
@ResponseBody @ResponseBody
public Map<String, Object> pageList(HttpServletRequest request, public Map<String, Object> pageList(HttpServletRequest request,
@RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "0") int start,
@RequestParam(required = false, defaultValue = "10") int length, @RequestParam(required = false, defaultValue = "10") int length,
int jobGroup, int jobId, int logStatus, String filterTime) { int jobGroup, int jobId, int logStatus, String filterTime) {
// valid permission // valid permission
JobInfoController.validPermission(request, jobGroup); // 仅管理员支持查询全部;普通用户仅支持查询有权限的 jobGroup JobInfoController.validPermission(request, jobGroup); // 仅管理员支持查询全部;普通用户仅支持查询有权限的 jobGroup
// parse param // parse param
Date triggerTimeStart = null; Date triggerTimeStart = null;
Date triggerTimeEnd = null; Date triggerTimeEnd = null;
if (filterTime!=null && filterTime.trim().length()>0) { if (filterTime != null && filterTime.trim().length() > 0) {
String[] temp = filterTime.split(" - "); String[] temp = filterTime.split(" - ");
if (temp.length == 2) { if (temp.length == 2) {
triggerTimeStart = DateUtil.parseDateTime(temp[0]); triggerTimeStart = DateUtil.parseDateTime(temp[0]);
triggerTimeEnd = DateUtil.parseDateTime(temp[1]); triggerTimeEnd = DateUtil.parseDateTime(temp[1]);
} }
} }
// page query // page query
List<XxlJobLog> list = xxlJobLogDao.pageList(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus); List<XxlJobLog> list = xxlJobLogDao.pageList(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
int list_count = xxlJobLogDao.pageListCount(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus); int list_count = xxlJobLogDao.pageListCount(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
// package result // package result
Map<String, Object> maps = new HashMap<String, Object>(); Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数 maps.put("recordsTotal", list_count); // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数 maps.put("recordsFiltered", list_count); // 过滤后的总记录数
maps.put("data", list); // 分页列表 maps.put("data", list); // 分页列表
return maps; return maps;
} }
@RequestMapping("/logDetailPage") @RequestMapping("/logDetailPage")
public String logDetailPage(int id, Model model){ public String logDetailPage(int id, Model model) {
// base check // base check
ReturnT<String> logStatue = ReturnT.SUCCESS; ReturnT<String> logStatue = ReturnT.SUCCESS;
XxlJobLog jobLog = xxlJobLogDao.load(id); XxlJobLog jobLog = xxlJobLogDao.load(id);
if (jobLog == null) { if (jobLog == null) {
throw new RuntimeException(I18nUtil.getString("joblog_logid_unvalid")); throw new RuntimeException(I18nUtil.getString("joblog_logid_unvalid"));
} }
model.addAttribute("triggerCode", jobLog.getTriggerCode()); model.addAttribute("triggerCode", jobLog.getTriggerCode());
model.addAttribute("handleCode", jobLog.getHandleCode()); model.addAttribute("handleCode", jobLog.getHandleCode());
model.addAttribute("executorAddress", jobLog.getExecutorAddress()); model.addAttribute("executorAddress", jobLog.getExecutorAddress());
model.addAttribute("triggerTime", jobLog.getTriggerTime().getTime()); model.addAttribute("triggerTime", jobLog.getTriggerTime().getTime());
model.addAttribute("logId", jobLog.getId()); model.addAttribute("logId", jobLog.getId());
return "joblog/joblog.detail"; return "joblog/joblog.detail";
} }
@RequestMapping("/logDetailCat") @RequestMapping("/logDetailCat")
@ResponseBody @ResponseBody
public ReturnT<LogResult> logDetailCat(String executorAddress, long triggerTime, long logId, int fromLineNum){ public ReturnT<LogResult> logDetailCat(String executorAddress, long triggerTime, long logId, int fromLineNum) {
try { try {
ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(executorAddress); ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(executorAddress);
ReturnT<LogResult> logResult = executorBiz.log(new LogParam(triggerTime, logId, fromLineNum)); ReturnT<LogResult> logResult = executorBiz.log(new LogParam(triggerTime, logId, fromLineNum));
// is end // is end
if (logResult.getContent()!=null && logResult.getContent().getFromLineNum() > logResult.getContent().getToLineNum()) { if (logResult.getContent() != null && logResult.getContent().getFromLineNum() > logResult.getContent().getToLineNum()) {
XxlJobLog jobLog = xxlJobLogDao.load(logId); XxlJobLog jobLog = xxlJobLogDao.load(logId);
if (jobLog.getHandleCode() > 0) { if (jobLog.getHandleCode() > 0) {
logResult.getContent().setEnd(true); logResult.getContent().setEnd(true);
} }
} }
return logResult; return logResult;
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
return new ReturnT<LogResult>(ReturnT.FAIL_CODE, e.getMessage()); return new ReturnT<LogResult>(ReturnT.FAIL_CODE, e.getMessage());
} }
} }
@RequestMapping("/logKill") @RequestMapping("/logKill")
@ResponseBody @ResponseBody
public ReturnT<String> logKill(int id){ public ReturnT<String> logKill(int id) {
// base check // base check
XxlJobLog log = xxlJobLogDao.load(id); XxlJobLog log = xxlJobLogDao.load(id);
XxlJobInfo jobInfo = xxlJobInfoDao.loadById(log.getJobId()); XxlJobInfo jobInfo = xxlJobInfoDao.loadById(log.getJobId());
if (jobInfo==null) { if (jobInfo == null) {
return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_jobid_unvalid")); return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_jobid_unvalid"));
} }
if (ReturnT.SUCCESS_CODE != log.getTriggerCode()) { if (ReturnT.SUCCESS_CODE != log.getTriggerCode()) {
return new ReturnT<String>(500, I18nUtil.getString("joblog_kill_log_limit")); return new ReturnT<String>(500, I18nUtil.getString("joblog_kill_log_limit"));
} }
// request of kill // request of kill
ReturnT<String> runResult = null; ReturnT<String> runResult = null;
try { try {
ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(log.getExecutorAddress()); ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(log.getExecutorAddress());
runResult = executorBiz.kill(new KillParam(jobInfo.getId())); runResult = executorBiz.kill(new KillParam(jobInfo.getId()));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
runResult = new ReturnT<String>(500, e.getMessage()); runResult = new ReturnT<String>(500, e.getMessage());
} }
if (ReturnT.SUCCESS_CODE == runResult.getCode()) { if (ReturnT.SUCCESS_CODE == runResult.getCode()) {
log.setHandleCode(ReturnT.FAIL_CODE); log.setHandleCode(ReturnT.FAIL_CODE);
log.setHandleMsg( I18nUtil.getString("joblog_kill_log_byman")+":" + (runResult.getMsg()!=null?runResult.getMsg():"")); log.setHandleMsg(I18nUtil.getString("joblog_kill_log_byman") + ":" + (runResult.getMsg() != null ? runResult.getMsg() : ""));
log.setHandleTime(new Date()); log.setHandleTime(new Date());
XxlJobCompleter.updateHandleInfoAndFinish(log); XxlJobCompleter.updateHandleInfoAndFinish(log);
return new ReturnT<String>(runResult.getMsg()); return new ReturnT<String>(runResult.getMsg());
} else { } else {
return new ReturnT<String>(500, runResult.getMsg()); return new ReturnT<String>(500, runResult.getMsg());
} }
} }
@RequestMapping("/clearLog") @RequestMapping("/clearLog")
@ResponseBody @ResponseBody
public ReturnT<String> clearLog(int jobGroup, int jobId, int type){ public ReturnT<String> clearLog(int jobGroup, int jobId, int type) {
Date clearBeforeTime = null; Date clearBeforeTime = null;
int clearBeforeNum = 0; int clearBeforeNum = 0;
if (type == 1) { if (type == 1) {
clearBeforeTime = DateUtil.addMonths(new Date(), -1); // 清理一个月之前日志数据 clearBeforeTime = DateUtil.addMonths(new Date(), -1); // 清理一个月之前日志数据
} else if (type == 2) { } else if (type == 2) {
clearBeforeTime = DateUtil.addMonths(new Date(), -3); // 清理三个月之前日志数据 clearBeforeTime = DateUtil.addMonths(new Date(), -3); // 清理三个月之前日志数据
} else if (type == 3) { } else if (type == 3) {
clearBeforeTime = DateUtil.addMonths(new Date(), -6); // 清理六个月之前日志数据 clearBeforeTime = DateUtil.addMonths(new Date(), -6); // 清理六个月之前日志数据
} else if (type == 4) { } else if (type == 4) {
clearBeforeTime = DateUtil.addYears(new Date(), -1); // 清理一年之前日志数据 clearBeforeTime = DateUtil.addYears(new Date(), -1); // 清理一年之前日志数据
} else if (type == 5) { } else if (type == 5) {
clearBeforeNum = 1000; // 清理一千条以前日志数据 clearBeforeNum = 1000; // 清理一千条以前日志数据
} else if (type == 6) { } else if (type == 6) {
clearBeforeNum = 10000; // 清理一万条以前日志数据 clearBeforeNum = 10000; // 清理一万条以前日志数据
} else if (type == 7) { } else if (type == 7) {
clearBeforeNum = 30000; // 清理三万条以前日志数据 clearBeforeNum = 30000; // 清理三万条以前日志数据
} else if (type == 8) { } else if (type == 8) {
clearBeforeNum = 100000; // 清理十万条以前日志数据 clearBeforeNum = 100000; // 清理十万条以前日志数据
} else if (type == 9) { } else if (type == 9) {
clearBeforeNum = 0; // 清理所有日志数据 clearBeforeNum = 0; // 清理所有日志数据
} else { } else {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_clean_type_unvalid")); return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_clean_type_unvalid"));
} }
List<Long> logIds = null; List<Long> logIds = null;
do { do {
logIds = xxlJobLogDao.findClearLogIds(jobGroup, jobId, clearBeforeTime, clearBeforeNum, 1000); logIds = xxlJobLogDao.findClearLogIds(jobGroup, jobId, clearBeforeTime, clearBeforeNum, 1000);
if (logIds!=null && logIds.size()>0) { if (logIds != null && logIds.size() > 0) {
xxlJobLogDao.clearLog(logIds); xxlJobLogDao.clearLog(logIds);
} }
} while (logIds!=null && logIds.size()>0); } while (logIds != null && logIds.size() > 0);
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
} }

View File

@ -57,17 +57,17 @@ public class UserController {
int list_count = xxlJobUserDao.pageListCount(start, length, username, role); int list_count = xxlJobUserDao.pageListCount(start, length, username, role);
// filter // filter
if (list!=null && list.size()>0) { if (list != null && list.size() > 0) {
for (XxlJobUser item: list) { for (XxlJobUser item : list) {
item.setPassword(null); item.setPassword(null);
} }
} }
// package result // package result
Map<String, Object> maps = new HashMap<String, Object>(); Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数 maps.put("recordsTotal", list_count); // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数 maps.put("recordsFiltered", list_count); // 过滤后的总记录数
maps.put("data", list); // 分页列表 maps.put("data", list); // 分页列表
return maps; return maps;
} }
@ -78,19 +78,19 @@ public class UserController {
// valid username // valid username
if (!StringUtils.hasText(xxlJobUser.getUsername())) { if (!StringUtils.hasText(xxlJobUser.getUsername())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_please_input")+I18nUtil.getString("user_username") ); return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_please_input") + I18nUtil.getString("user_username"));
} }
xxlJobUser.setUsername(xxlJobUser.getUsername().trim()); xxlJobUser.setUsername(xxlJobUser.getUsername().trim());
if (!(xxlJobUser.getUsername().length()>=4 && xxlJobUser.getUsername().length()<=20)) { if (!(xxlJobUser.getUsername().length() >= 4 && xxlJobUser.getUsername().length() <= 20)) {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit")+"[4-20]" ); return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit") + "[4-20]");
} }
// valid password // valid password
if (!StringUtils.hasText(xxlJobUser.getPassword())) { if (!StringUtils.hasText(xxlJobUser.getPassword())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_please_input")+I18nUtil.getString("user_password") ); return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_please_input") + I18nUtil.getString("user_password"));
} }
xxlJobUser.setPassword(xxlJobUser.getPassword().trim()); xxlJobUser.setPassword(xxlJobUser.getPassword().trim());
if (!(xxlJobUser.getPassword().length()>=4 && xxlJobUser.getPassword().length()<=20)) { if (!(xxlJobUser.getPassword().length() >= 4 && xxlJobUser.getPassword().length() <= 20)) {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit")+"[4-20]" ); return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit") + "[4-20]");
} }
// md5 password // md5 password
xxlJobUser.setPassword(DigestUtils.md5DigestAsHex(xxlJobUser.getPassword().getBytes())); xxlJobUser.setPassword(DigestUtils.md5DigestAsHex(xxlJobUser.getPassword().getBytes()));
@ -98,7 +98,7 @@ public class UserController {
// check repeat // check repeat
XxlJobUser existUser = xxlJobUserDao.loadByUserName(xxlJobUser.getUsername()); XxlJobUser existUser = xxlJobUserDao.loadByUserName(xxlJobUser.getUsername());
if (existUser != null) { if (existUser != null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("user_username_repeat") ); return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("user_username_repeat"));
} }
// write // write
@ -120,8 +120,8 @@ public class UserController {
// valid password // valid password
if (StringUtils.hasText(xxlJobUser.getPassword())) { if (StringUtils.hasText(xxlJobUser.getPassword())) {
xxlJobUser.setPassword(xxlJobUser.getPassword().trim()); xxlJobUser.setPassword(xxlJobUser.getPassword().trim());
if (!(xxlJobUser.getPassword().length()>=4 && xxlJobUser.getPassword().length()<=20)) { if (!(xxlJobUser.getPassword().length() >= 4 && xxlJobUser.getPassword().length() <= 20)) {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit")+"[4-20]" ); return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit") + "[4-20]");
} }
// md5 password // md5 password
xxlJobUser.setPassword(DigestUtils.md5DigestAsHex(xxlJobUser.getPassword().getBytes())); xxlJobUser.setPassword(DigestUtils.md5DigestAsHex(xxlJobUser.getPassword().getBytes()));
@ -151,15 +151,15 @@ public class UserController {
@RequestMapping("/updatePwd") @RequestMapping("/updatePwd")
@ResponseBody @ResponseBody
public ReturnT<String> updatePwd(HttpServletRequest request, String password){ public ReturnT<String> updatePwd(HttpServletRequest request, String password) {
// valid password // valid password
if (password==null || password.trim().length()==0){ if (password == null || password.trim().length() == 0) {
return new ReturnT<String>(ReturnT.FAIL.getCode(), "密码不可为空"); return new ReturnT<String>(ReturnT.FAIL.getCode(), "密码不可为空");
} }
password = password.trim(); password = password.trim();
if (!(password.length()>=4 && password.length()<=20)) { if (!(password.length() >= 4 && password.length() <= 20)) {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit")+"[4-20]" ); return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit") + "[4-20]");
} }
// md5 password // md5 password

View File

@ -8,22 +8,23 @@ import java.lang.annotation.Target;
/** /**
* *
*
* @author xuxueli 2015-12-12 18:29:02 * @author xuxueli 2015-12-12 18:29:02
*/ */
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface PermissionLimit { public @interface PermissionLimit {
/** /**
* () * ()
*/ */
boolean limit() default true; boolean limit() default true;
/** /**
* *
* *
* @return * @return
*/ */
boolean adminuser() default false; boolean adminuser() default false;
} }

View File

@ -19,25 +19,24 @@ import java.util.HashMap;
@Component @Component
public class CookieInterceptor implements AsyncHandlerInterceptor { public class CookieInterceptor implements AsyncHandlerInterceptor {
@Override @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception { ModelAndView modelAndView) throws Exception {
// cookie // cookie
if (modelAndView!=null && request.getCookies()!=null && request.getCookies().length>0) { if (modelAndView != null && request.getCookies() != null && request.getCookies().length > 0) {
HashMap<String, Cookie> cookieMap = new HashMap<String, Cookie>(); HashMap<String, Cookie> cookieMap = new HashMap<String, Cookie>();
for (Cookie ck : request.getCookies()) { for (Cookie ck : request.getCookies()) {
cookieMap.put(ck.getName(), ck); cookieMap.put(ck.getName(), ck);
} }
modelAndView.addObject("cookieMap", cookieMap); modelAndView.addObject("cookieMap", cookieMap);
} }
// static method // static method
if (modelAndView != null) { if (modelAndView != null) {
modelAndView.addObject("I18nUtil", FtlUtil.generateStaticModel(I18nUtil.class.getName())); modelAndView.addObject("I18nUtil", FtlUtil.generateStaticModel(I18nUtil.class.getName()));
} }
AsyncHandlerInterceptor.super.postHandle(request, response, handler, modelAndView); }
}
} }

View File

@ -20,40 +20,40 @@ import javax.servlet.http.HttpServletResponse;
@Component @Component
public class PermissionInterceptor implements AsyncHandlerInterceptor { public class PermissionInterceptor implements AsyncHandlerInterceptor {
@Resource @Resource
private LoginService loginService; private LoginService loginService;
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) { if (!(handler instanceof HandlerMethod)) {
return AsyncHandlerInterceptor.super.preHandle(request, response, handler); return true; // proceed with the next interceptor
} }
// if need login // if need login
boolean needLogin = true; boolean needLogin = true;
boolean needAdminuser = false; boolean needAdminuser = false;
HandlerMethod method = (HandlerMethod)handler; HandlerMethod method = (HandlerMethod) handler;
PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class); PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class);
if (permission!=null) { if (permission != null) {
needLogin = permission.limit(); needLogin = permission.limit();
needAdminuser = permission.adminuser(); needAdminuser = permission.adminuser();
} }
if (needLogin) { if (needLogin) {
XxlJobUser loginUser = loginService.ifLogin(request, response); XxlJobUser loginUser = loginService.ifLogin(request, response);
if (loginUser == null) { if (loginUser == null) {
response.setStatus(302); response.setStatus(302);
response.setHeader("location", request.getContextPath()+"/toLogin"); response.setHeader("location", request.getContextPath() + "/toLogin");
return false; return false;
} }
if (needAdminuser && loginUser.getRole()!=1) { if (needAdminuser && loginUser.getRole() != 1) {
throw new RuntimeException(I18nUtil.getString("system_permission_limit")); throw new RuntimeException(I18nUtil.getString("system_permission_limit"));
} }
request.setAttribute(LoginService.LOGIN_IDENTITY_KEY, loginUser); request.setAttribute(LoginService.LOGIN_IDENTITY_KEY, loginUser);
} }
return AsyncHandlerInterceptor.super.preHandle(request, response, handler); return true; // proceed with the next interceptor
} }
} }

View File

@ -1,8 +1,8 @@
package com.xxl.job.admin.controller.resolver; package com.xxl.job.admin.controller.resolver;
import com.xxl.job.admin.core.exception.XxlJobException; import com.xxl.job.admin.core.exception.XxlJobException;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.admin.core.util.JacksonUtil; import com.xxl.job.admin.core.util.JacksonUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -22,45 +22,45 @@ import java.io.IOException;
*/ */
@Component @Component
public class WebExceptionResolver implements HandlerExceptionResolver { public class WebExceptionResolver implements HandlerExceptionResolver {
private static transient Logger logger = LoggerFactory.getLogger(WebExceptionResolver.class); private static transient Logger logger = LoggerFactory.getLogger(WebExceptionResolver.class);
@Override @Override
public ModelAndView resolveException(HttpServletRequest request, public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) { HttpServletResponse response, Object handler, Exception ex) {
if (!(ex instanceof XxlJobException)) { if (!(ex instanceof XxlJobException)) {
logger.error("WebExceptionResolver:{}", ex); logger.error("WebExceptionResolver:{}", ex);
} }
// if json // if json
boolean isJson = false; boolean isJson = false;
if (handler instanceof HandlerMethod) { if (handler instanceof HandlerMethod) {
HandlerMethod method = (HandlerMethod)handler; HandlerMethod method = (HandlerMethod) handler;
ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class); ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
if (responseBody != null) { if (responseBody != null) {
isJson = true; isJson = true;
} }
} }
// error result // error result
ReturnT<String> errorResult = new ReturnT<String>(ReturnT.FAIL_CODE, ex.toString().replaceAll("\n", "<br/>")); ReturnT<String> errorResult = new ReturnT<String>(ReturnT.FAIL_CODE, ex.toString().replaceAll("\n", "<br/>"));
// response // response
ModelAndView mv = new ModelAndView(); ModelAndView mv = new ModelAndView();
if (isJson) { if (isJson) {
try { try {
response.setContentType("application/json;charset=utf-8"); response.setContentType("application/json;charset=utf-8");
response.getWriter().print(JacksonUtil.writeValueAsString(errorResult)); response.getWriter().print(JacksonUtil.writeValueAsString(errorResult));
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
return mv; return mv;
} else { } else {
mv.addObject("exceptionMsg", errorResult.getMsg()); mv.addObject("exceptionMsg", errorResult.getMsg());
mv.setViewName("/common/common.exception"); mv.setViewName("/common/common.exception");
return mv; return mv;
} }
} }
} }

View File

@ -44,9 +44,9 @@ public class JobAlarmer implements ApplicationContextAware, InitializingBean {
public boolean alarm(XxlJobInfo info, XxlJobLog jobLog) { public boolean alarm(XxlJobInfo info, XxlJobLog jobLog) {
boolean result = false; boolean result = false;
if (jobAlarmList!=null && jobAlarmList.size()>0) { if (jobAlarmList != null && jobAlarmList.size() > 0) {
result = true; // success means all-success result = true; // success means all-success
for (JobAlarm alarm: jobAlarmList) { for (JobAlarm alarm : jobAlarmList) {
boolean resultItem = false; boolean resultItem = false;
try { try {
resultItem = alarm.doAlarm(info, jobLog); resultItem = alarm.doAlarm(info, jobLog);

View File

@ -32,18 +32,19 @@ public class EmailJobAlarm implements JobAlarm {
* *
* @param jobLog * @param jobLog
*/ */
public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog){ @Override
public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
boolean alarmResult = true; boolean alarmResult = true;
// send monitor email // send monitor email
if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) { if (info != null && info.getAlarmEmail() != null && info.getAlarmEmail().trim().length() > 0) {
// alarmContent // alarmContent
String alarmContent = "Alarm Job LogId=" + jobLog.getId(); String alarmContent = "Alarm Job LogId=" + jobLog.getId();
if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) { if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
alarmContent += "<br>TriggerMsg=<br>" + jobLog.getTriggerMsg(); alarmContent += "<br>TriggerMsg=<br>" + jobLog.getTriggerMsg();
} }
if (jobLog.getHandleCode()>0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) { if (jobLog.getHandleCode() > 0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
alarmContent += "<br>HandleCode=" + jobLog.getHandleMsg(); alarmContent += "<br>HandleCode=" + jobLog.getHandleMsg();
} }
@ -52,13 +53,13 @@ public class EmailJobAlarm implements JobAlarm {
String personal = I18nUtil.getString("admin_name_full"); String personal = I18nUtil.getString("admin_name_full");
String title = I18nUtil.getString("jobconf_monitor"); String title = I18nUtil.getString("jobconf_monitor");
String content = MessageFormat.format(loadEmailJobAlarmTemplate(), String content = MessageFormat.format(loadEmailJobAlarmTemplate(),
group!=null?group.getTitle():"null", group != null ? group.getTitle() : "null",
info.getId(), info.getId(),
info.getJobDesc(), info.getJobDesc(),
alarmContent); alarmContent);
Set<String> emailSet = new HashSet<String>(Arrays.asList(info.getAlarmEmail().split(","))); Set<String> emailSet = new HashSet<String>(Arrays.asList(info.getAlarmEmail().split(",")));
for (String email: emailSet) { for (String email : emailSet) {
// make mail // make mail
try { try {
@ -88,28 +89,28 @@ public class EmailJobAlarm implements JobAlarm {
* *
* @return * @return
*/ */
private static final String loadEmailJobAlarmTemplate(){ private static final String loadEmailJobAlarmTemplate() {
String mailBodyTemplate = "<h5>" + I18nUtil.getString("jobconf_monitor_detail") + "</span>" + String mailBodyTemplate = "<h5>" + I18nUtil.getString("jobconf_monitor_detail") + "</span>" +
"<table border=\"1\" cellpadding=\"3\" style=\"border-collapse:collapse; width:80%;\" >\n" + "<table border=\"1\" cellpadding=\"3\" style=\"border-collapse:collapse; width:80%;\" >\n" +
" <thead style=\"font-weight: bold;color: #ffffff;background-color: #ff8c00;\" >" + " <thead style=\"font-weight: bold;color: #ffffff;background-color: #ff8c00;\" >" +
" <tr>\n" + " <tr>\n" +
" <td width=\"20%\" >"+ I18nUtil.getString("jobinfo_field_jobgroup") +"</td>\n" + " <td width=\"20%\" >" + I18nUtil.getString("jobinfo_field_jobgroup") + "</td>\n" +
" <td width=\"10%\" >"+ I18nUtil.getString("jobinfo_field_id") +"</td>\n" + " <td width=\"10%\" >" + I18nUtil.getString("jobinfo_field_id") + "</td>\n" +
" <td width=\"20%\" >"+ I18nUtil.getString("jobinfo_field_jobdesc") +"</td>\n" + " <td width=\"20%\" >" + I18nUtil.getString("jobinfo_field_jobdesc") + "</td>\n" +
" <td width=\"10%\" >"+ I18nUtil.getString("jobconf_monitor_alarm_title") +"</td>\n" + " <td width=\"10%\" >" + I18nUtil.getString("jobconf_monitor_alarm_title") + "</td>\n" +
" <td width=\"40%\" >"+ I18nUtil.getString("jobconf_monitor_alarm_content") +"</td>\n" + " <td width=\"40%\" >" + I18nUtil.getString("jobconf_monitor_alarm_content") + "</td>\n" +
" </tr>\n" + " </tr>\n" +
" </thead>\n" + " </thead>\n" +
" <tbody>\n" + " <tbody>\n" +
" <tr>\n" + " <tr>\n" +
" <td>{0}</td>\n" + " <td>{0}</td>\n" +
" <td>{1}</td>\n" + " <td>{1}</td>\n" +
" <td>{2}</td>\n" + " <td>{2}</td>\n" +
" <td>"+ I18nUtil.getString("jobconf_monitor_alarm_type") +"</td>\n" + " <td>" + I18nUtil.getString("jobconf_monitor_alarm_type") + "</td>\n" +
" <td>{3}</td>\n" + " <td>{3}</td>\n" +
" </tr>\n" + " </tr>\n" +
" </tbody>\n" + " </tbody>\n" +
"</table>"; "</table>";
return mailBodyTemplate; return mailBodyTemplate;
} }

View File

@ -32,7 +32,7 @@ public class XxlJobCompleter {
// text最大64kb 避免长度过长 // text最大64kb 避免长度过长
if (xxlJobLog.getHandleMsg().length() > 15000) { if (xxlJobLog.getHandleMsg().length() > 15000) {
xxlJobLog.setHandleMsg( xxlJobLog.getHandleMsg().substring(0, 15000) ); xxlJobLog.setHandleMsg(xxlJobLog.getHandleMsg().substring(0, 15000));
} }
// fresh handle // fresh handle
@ -43,18 +43,18 @@ public class XxlJobCompleter {
/** /**
* do somethind to finish job * do somethind to finish job
*/ */
private static void finishJob(XxlJobLog xxlJobLog){ private static void finishJob(XxlJobLog xxlJobLog) {
// 1、handle success, to trigger child job // 1、handle success, to trigger child job
String triggerChildMsg = null; String triggerChildMsg = null;
if (XxlJobContext.HANDLE_COCE_SUCCESS == xxlJobLog.getHandleCode()) { if (XxlJobContext.HANDLE_CODE_SUCCESS == xxlJobLog.getHandleCode()) {
XxlJobInfo xxlJobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(xxlJobLog.getJobId()); XxlJobInfo xxlJobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(xxlJobLog.getJobId());
if (xxlJobInfo!=null && xxlJobInfo.getChildJobId()!=null && xxlJobInfo.getChildJobId().trim().length()>0) { if (xxlJobInfo != null && xxlJobInfo.getChildJobId() != null && xxlJobInfo.getChildJobId().trim().length() > 0) {
triggerChildMsg = "<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_child_run") +"<<<<<<<<<<< </span><br>"; triggerChildMsg = "<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>" + I18nUtil.getString("jobconf_trigger_child_run") + "<<<<<<<<<<< </span><br>";
String[] childJobIds = xxlJobInfo.getChildJobId().split(","); String[] childJobIds = xxlJobInfo.getChildJobId().split(",");
for (int i = 0; i < childJobIds.length; i++) { for (int i = 0; i < childJobIds.length; i++) {
int childJobId = (childJobIds[i]!=null && childJobIds[i].trim().length()>0 && isNumeric(childJobIds[i]))?Integer.valueOf(childJobIds[i]):-1; int childJobId = (childJobIds[i] != null && childJobIds[i].trim().length() > 0 && isNumeric(childJobIds[i])) ? Integer.valueOf(childJobIds[i]) : -1;
if (childJobId > 0) { if (childJobId > 0) {
JobTriggerPoolHelper.trigger(childJobId, TriggerTypeEnum.PARENT, -1, null, null, null); JobTriggerPoolHelper.trigger(childJobId, TriggerTypeEnum.PARENT, -1, null, null, null);
@ -62,16 +62,16 @@ public class XxlJobCompleter {
// add msg // add msg
triggerChildMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg1"), triggerChildMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg1"),
(i+1), (i + 1),
childJobIds.length, childJobIds.length,
childJobIds[i], childJobIds[i],
(triggerChildResult.getCode()==ReturnT.SUCCESS_CODE?I18nUtil.getString("system_success"):I18nUtil.getString("system_fail")), (triggerChildResult.getCode() == ReturnT.SUCCESS_CODE ? I18nUtil.getString("system_success") : I18nUtil.getString("system_fail")),
triggerChildResult.getMsg()); triggerChildResult.getMsg());
} else { } else {
triggerChildMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg2"), triggerChildMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg2"),
(i+1), (i + 1),
childJobIds.length, childJobIds.length,
childJobIds[i]); childJobIds[i]);
} }
} }
@ -79,7 +79,7 @@ public class XxlJobCompleter {
} }
if (triggerChildMsg != null) { if (triggerChildMsg != null) {
xxlJobLog.setHandleMsg( xxlJobLog.getHandleMsg() + triggerChildMsg ); xxlJobLog.setHandleMsg(xxlJobLog.getHandleMsg() + triggerChildMsg);
} }
// 2、fix_delay trigger next // 2、fix_delay trigger next
@ -87,7 +87,7 @@ public class XxlJobCompleter {
} }
private static boolean isNumeric(String str){ private static boolean isNumeric(String str) {
try { try {
int result = Integer.valueOf(str); int result = Integer.valueOf(str);
return true; return true;

View File

@ -23,6 +23,7 @@ import java.util.Arrays;
public class XxlJobAdminConfig implements InitializingBean, DisposableBean { public class XxlJobAdminConfig implements InitializingBean, DisposableBean {
private static XxlJobAdminConfig adminConfig = null; private static XxlJobAdminConfig adminConfig = null;
public static XxlJobAdminConfig getAdminConfig() { public static XxlJobAdminConfig getAdminConfig() {
return adminConfig; return adminConfig;
} }

View File

@ -19,16 +19,7 @@ package com.xxl.job.admin.core.cron;
import java.io.Serializable; import java.io.Serializable;
import java.text.ParseException; import java.text.ParseException;
import java.util.Calendar; import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.TreeSet;
/** /**
* Provides a parser and evaluator for unix-like cron expressions. Cron * Provides a parser and evaluator for unix-like cron expressions. Cron
@ -191,13 +182,11 @@ import java.util.TreeSet;
* </ul> * </ul>
* </p> * </p>
* *
*
* @author Sharada Jambula, James House * @author Sharada Jambula, James House
* @author Contributions from Mads Henderson * @author Contributions from Mads Henderson
* @author Refactoring from CronTrigger to CronExpression by Aaron Craven * @author Refactoring from CronTrigger to CronExpression by Aaron Craven
* * <p>
* Borrowed from quartz v2.3.1 * Borrowed from quartz v2.3.1
*
*/ */
public final class CronExpression implements Serializable, Cloneable { public final class CronExpression implements Serializable, Cloneable {
@ -217,6 +206,7 @@ public final class CronExpression implements Serializable, Cloneable {
protected static final Map<String, Integer> monthMap = new HashMap<String, Integer>(20); protected static final Map<String, Integer> monthMap = new HashMap<String, Integer>(20);
protected static final Map<String, Integer> dayMap = new HashMap<String, Integer>(60); protected static final Map<String, Integer> dayMap = new HashMap<String, Integer>(60);
static { static {
monthMap.put("JAN", 0); monthMap.put("JAN", 0);
monthMap.put("FEB", 1); monthMap.put("FEB", 1);
@ -265,9 +255,8 @@ public final class CronExpression implements Serializable, Cloneable {
* *
* @param cronExpression String representation of the cron expression the * @param cronExpression String representation of the cron expression the
* new object should represent * new object should represent
* @throws java.text.ParseException * @throws ParseException if the string expression cannot be parsed into a valid
* if the string expression cannot be parsed into a valid * <CODE>CronExpression</CODE>
* <CODE>CronExpression</CODE>
*/ */
public CronExpression(String cronExpression) throws ParseException { public CronExpression(String cronExpression) throws ParseException {
if (cronExpression == null) { if (cronExpression == null) {
@ -283,8 +272,7 @@ public final class CronExpression implements Serializable, Cloneable {
* Constructs a new {@code CronExpression} as a copy of an existing * Constructs a new {@code CronExpression} as a copy of an existing
* instance. * instance.
* *
* @param expression * @param expression The existing cron expression to be copied
* The existing cron expression to be copied
*/ */
public CronExpression(CronExpression expression) { public CronExpression(CronExpression expression) {
/* /*
@ -310,7 +298,7 @@ public final class CronExpression implements Serializable, Cloneable {
* *
* @param date the date to evaluate * @param date the date to evaluate
* @return a boolean indicating whether the given date satisfies the cron * @return a boolean indicating whether the given date satisfies the cron
* expression * expression
*/ */
public boolean isSatisfiedBy(Date date) { public boolean isSatisfiedBy(Date date) {
Calendar testDateCal = Calendar.getInstance(getTimeZone()); Calendar testDateCal = Calendar.getInstance(getTimeZone());
@ -363,7 +351,7 @@ public final class CronExpression implements Serializable, Cloneable {
// the second immediately following it. // the second immediately following it.
while (difference == 1000) { while (difference == 1000) {
newDate = getTimeAfter(lastDate); newDate = getTimeAfter(lastDate);
if(newDate == null) if (newDate == null)
break; break;
difference = newDate.getTime() - lastDate.getTime(); difference = newDate.getTime() - lastDate.getTime();
@ -412,7 +400,7 @@ public final class CronExpression implements Serializable, Cloneable {
* *
* @param cronExpression the expression to evaluate * @param cronExpression the expression to evaluate
* @return a boolean indicating whether the given expression is a valid cron * @return a boolean indicating whether the given expression is a valid cron
* expression * expression
*/ */
public static boolean isValidExpression(String cronExpression) { public static boolean isValidExpression(String cronExpression) {
@ -467,20 +455,20 @@ public final class CronExpression implements Serializable, Cloneable {
int exprOn = SECOND; int exprOn = SECOND;
StringTokenizer exprsTok = new StringTokenizer(expression, " \t", StringTokenizer exprsTok = new StringTokenizer(expression, " \t",
false); false);
while (exprsTok.hasMoreTokens() && exprOn <= YEAR) { while (exprsTok.hasMoreTokens() && exprOn <= YEAR) {
String expr = exprsTok.nextToken().trim(); String expr = exprsTok.nextToken().trim();
// throw an exception if L is used with other days of the month // throw an exception if L is used with other days of the month
if(exprOn == DAY_OF_MONTH && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) { if (exprOn == DAY_OF_MONTH && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
throw new ParseException("Support for specifying 'L' and 'LW' with other days of the month is not implemented", -1); throw new ParseException("Support for specifying 'L' and 'LW' with other days of the month is not implemented", -1);
} }
// throw an exception if L is used with other days of the week // throw an exception if L is used with other days of the week
if(exprOn == DAY_OF_WEEK && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) { if (exprOn == DAY_OF_WEEK && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
throw new ParseException("Support for specifying 'L' with other days of the week is not implemented", -1); throw new ParseException("Support for specifying 'L' with other days of the week is not implemented", -1);
} }
if(exprOn == DAY_OF_WEEK && expr.indexOf('#') != -1 && expr.indexOf('#', expr.indexOf('#') +1) != -1) { if (exprOn == DAY_OF_WEEK && expr.indexOf('#') != -1 && expr.indexOf('#', expr.indexOf('#') + 1) != -1) {
throw new ParseException("Support for specifying multiple \"nth\" days is not implemented.", -1); throw new ParseException("Support for specifying multiple \"nth\" days is not implemented.", -1);
} }
@ -495,7 +483,7 @@ public final class CronExpression implements Serializable, Cloneable {
if (exprOn <= DAY_OF_WEEK) { if (exprOn <= DAY_OF_WEEK) {
throw new ParseException("Unexpected end of expression.", throw new ParseException("Unexpected end of expression.",
expression.length()); expression.length());
} }
if (exprOn <= YEAR) { if (exprOn <= YEAR) {
@ -512,14 +500,14 @@ public final class CronExpression implements Serializable, Cloneable {
if (!dayOfMSpec || dayOfWSpec) { if (!dayOfMSpec || dayOfWSpec) {
if (!dayOfWSpec || dayOfMSpec) { if (!dayOfWSpec || dayOfMSpec) {
throw new ParseException( throw new ParseException(
"Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.", 0); "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.", 0);
} }
} }
} catch (ParseException pe) { } catch (ParseException pe) {
throw pe; throw pe;
} catch (Exception e) { } catch (Exception e) {
throw new ParseException("Illegal cron expression format (" throw new ParseException("Illegal cron expression format ("
+ e.toString() + ")", 0); + e.toString() + ")", 0);
} }
} }
@ -556,7 +544,7 @@ public final class CronExpression implements Serializable, Cloneable {
sval = getDayOfWeekNumber(sub); sval = getDayOfWeekNumber(sub);
if (sval < 0) { if (sval < 0) {
throw new ParseException("Invalid Day-of-Week value: '" throw new ParseException("Invalid Day-of-Week value: '"
+ sub + "'", i); + sub + "'", i);
} }
if (s.length() > i + 3) { if (s.length() > i + 3) {
c = s.charAt(i + 3); c = s.charAt(i + 3);
@ -566,8 +554,8 @@ public final class CronExpression implements Serializable, Cloneable {
eval = getDayOfWeekNumber(sub); eval = getDayOfWeekNumber(sub);
if (eval < 0) { if (eval < 0) {
throw new ParseException( throw new ParseException(
"Invalid Day-of-Week value: '" + sub "Invalid Day-of-Week value: '" + sub
+ "'", i); + "'", i);
} }
} else if (c == '#') { } else if (c == '#') {
try { try {
@ -578,8 +566,8 @@ public final class CronExpression implements Serializable, Cloneable {
} }
} catch (Exception e) { } catch (Exception e) {
throw new ParseException( throw new ParseException(
"A numeric value between 1 and 5 must follow the '#' option", "A numeric value between 1 and 5 must follow the '#' option",
i); i);
} }
} else if (c == 'L') { } else if (c == 'L') {
lastdayOfWeek = true; lastdayOfWeek = true;
@ -589,8 +577,8 @@ public final class CronExpression implements Serializable, Cloneable {
} else { } else {
throw new ParseException( throw new ParseException(
"Illegal characters for this position: '" + sub + "'", "Illegal characters for this position: '" + sub + "'",
i); i);
} }
if (eval != -1) { if (eval != -1) {
incr = 1; incr = 1;
@ -602,21 +590,21 @@ public final class CronExpression implements Serializable, Cloneable {
if (c == '?') { if (c == '?') {
i++; i++;
if ((i + 1) < s.length() if ((i + 1) < s.length()
&& (s.charAt(i) != ' ' && s.charAt(i + 1) != '\t')) { && (s.charAt(i) != ' ' && s.charAt(i + 1) != '\t')) {
throw new ParseException("Illegal character after '?': " throw new ParseException("Illegal character after '?': "
+ s.charAt(i), i); + s.charAt(i), i);
} }
if (type != DAY_OF_WEEK && type != DAY_OF_MONTH) { if (type != DAY_OF_WEEK && type != DAY_OF_MONTH) {
throw new ParseException( throw new ParseException(
"'?' can only be specified for Day-of-Month or Day-of-Week.", "'?' can only be specified for Day-of-Month or Day-of-Week.",
i); i);
} }
if (type == DAY_OF_WEEK && !lastdayOfMonth) { if (type == DAY_OF_WEEK && !lastdayOfMonth) {
int val = daysOfMonth.last(); int val = daysOfMonth.last();
if (val == NO_SPEC_INT) { if (val == NO_SPEC_INT) {
throw new ParseException( throw new ParseException(
"'?' can only be specified for Day-of-Month -OR- Day-of-Week.", "'?' can only be specified for Day-of-Month -OR- Day-of-Week.",
i); i);
} }
} }
@ -629,8 +617,8 @@ public final class CronExpression implements Serializable, Cloneable {
addToSet(ALL_SPEC_INT, -1, incr, type); addToSet(ALL_SPEC_INT, -1, incr, type);
return i + 1; return i + 1;
} else if (c == '/' } else if (c == '/'
&& ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s && ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s
.charAt(i + 1) == '\t')) { .charAt(i + 1) == '\t')) {
throw new ParseException("'/' must be followed by an integer.", i); throw new ParseException("'/' must be followed by an integer.", i);
} else if (c == '*') { } else if (c == '*') {
i++; i++;
@ -663,18 +651,18 @@ public final class CronExpression implements Serializable, Cloneable {
if (type == DAY_OF_WEEK) { if (type == DAY_OF_WEEK) {
addToSet(7, 7, 0, type); addToSet(7, 7, 0, type);
} }
if(type == DAY_OF_MONTH && s.length() > i) { if (type == DAY_OF_MONTH && s.length() > i) {
c = s.charAt(i); c = s.charAt(i);
if(c == '-') { if (c == '-') {
ValueSet vs = getValue(0, s, i+1); ValueSet vs = getValue(0, s, i + 1);
lastdayOffset = vs.value; lastdayOffset = vs.value;
if(lastdayOffset > 30) if (lastdayOffset > 30)
throw new ParseException("Offset from last day must be <= 30", i+1); throw new ParseException("Offset from last day must be <= 30", i + 1);
i = vs.pos; i = vs.pos;
} }
if(s.length() > i) { if (s.length() > i) {
c = s.charAt(i); c = s.charAt(i);
if(c == 'W') { if (c == 'W') {
nearestWeekday = true; nearestWeekday = true;
i++; i++;
} }
@ -732,7 +720,7 @@ public final class CronExpression implements Serializable, Cloneable {
if (c == 'L') { if (c == 'L') {
if (type == DAY_OF_WEEK) { if (type == DAY_OF_WEEK) {
if(val < 1 || val > 7) if (val < 1 || val > 7)
throw new ParseException("Day-of-Week values must be between 1 and 7", -1); throw new ParseException("Day-of-Week values must be between 1 and 7", -1);
lastdayOfWeek = true; lastdayOfWeek = true;
} else { } else {
@ -750,7 +738,7 @@ public final class CronExpression implements Serializable, Cloneable {
} else { } else {
throw new ParseException("'W' option is not valid here. (pos=" + i + ")", i); throw new ParseException("'W' option is not valid here. (pos=" + i + ")", i);
} }
if(val > 31) if (val > 31)
throw new ParseException("The 'W' option does not make sense with values larger than 31 (max number of days in a month)", i); throw new ParseException("The 'W' option does not make sense with values larger than 31 (max number of days in a month)", i);
TreeSet<Integer> set = getSet(type); TreeSet<Integer> set = getSet(type);
set.add(val); set.add(val);
@ -770,8 +758,8 @@ public final class CronExpression implements Serializable, Cloneable {
} }
} catch (Exception e) { } catch (Exception e) {
throw new ParseException( throw new ParseException(
"A numeric value between 1 and 5 must follow the '#' option", "A numeric value between 1 and 5 must follow the '#' option",
i); i);
} }
TreeSet<Integer> set = getSet(type); TreeSet<Integer> set = getSet(type);
@ -972,30 +960,30 @@ public final class CronExpression implements Serializable, Cloneable {
if (type == SECOND || type == MINUTE) { if (type == SECOND || type == MINUTE) {
if ((val < 0 || val > 59 || end > 59) && (val != ALL_SPEC_INT)) { if ((val < 0 || val > 59 || end > 59) && (val != ALL_SPEC_INT)) {
throw new ParseException( throw new ParseException(
"Minute and Second values must be between 0 and 59", "Minute and Second values must be between 0 and 59",
-1); -1);
} }
} else if (type == HOUR) { } else if (type == HOUR) {
if ((val < 0 || val > 23 || end > 23) && (val != ALL_SPEC_INT)) { if ((val < 0 || val > 23 || end > 23) && (val != ALL_SPEC_INT)) {
throw new ParseException( throw new ParseException(
"Hour values must be between 0 and 23", -1); "Hour values must be between 0 and 23", -1);
} }
} else if (type == DAY_OF_MONTH) { } else if (type == DAY_OF_MONTH) {
if ((val < 1 || val > 31 || end > 31) && (val != ALL_SPEC_INT) if ((val < 1 || val > 31 || end > 31) && (val != ALL_SPEC_INT)
&& (val != NO_SPEC_INT)) { && (val != NO_SPEC_INT)) {
throw new ParseException( throw new ParseException(
"Day of month values must be between 1 and 31", -1); "Day of month values must be between 1 and 31", -1);
} }
} else if (type == MONTH) { } else if (type == MONTH) {
if ((val < 1 || val > 12 || end > 12) && (val != ALL_SPEC_INT)) { if ((val < 1 || val > 12 || end > 12) && (val != ALL_SPEC_INT)) {
throw new ParseException( throw new ParseException(
"Month values must be between 1 and 12", -1); "Month values must be between 1 and 12", -1);
} }
} else if (type == DAY_OF_WEEK) { } else if (type == DAY_OF_WEEK) {
if ((val == 0 || val > 7 || end > 7) && (val != ALL_SPEC_INT) if ((val == 0 || val > 7 || end > 7) && (val != ALL_SPEC_INT)
&& (val != NO_SPEC_INT)) { && (val != NO_SPEC_INT)) {
throw new ParseException( throw new ParseException(
"Day-of-Week values must be between 1 and 7", -1); "Day-of-Week values must be between 1 and 7", -1);
} }
} }
@ -1067,14 +1055,28 @@ public final class CronExpression implements Serializable, Cloneable {
int max = -1; int max = -1;
if (stopAt < startAt) { if (stopAt < startAt) {
switch (type) { switch (type) {
case SECOND : max = 60; break; case SECOND:
case MINUTE : max = 60; break; max = 60;
case HOUR : max = 24; break; break;
case MONTH : max = 12; break; case MINUTE:
case DAY_OF_WEEK : max = 7; break; max = 60;
case DAY_OF_MONTH : max = 31; break; break;
case YEAR : throw new IllegalArgumentException("Start year must be less than stop year"); case HOUR:
default : throw new IllegalArgumentException("Unexpected type encountered"); max = 24;
break;
case MONTH:
max = 12;
break;
case DAY_OF_WEEK:
max = 7;
break;
case DAY_OF_MONTH:
max = 31;
break;
case YEAR:
throw new IllegalArgumentException("Start year must be less than stop year");
default:
throw new IllegalArgumentException("Unexpected type encountered");
} }
stopAt += max; stopAt += max;
} }
@ -1088,7 +1090,7 @@ public final class CronExpression implements Serializable, Cloneable {
int i2 = i % max; int i2 = i % max;
// 1-indexed ranges should not include 0, and should include their max // 1-indexed ranges should not include 0, and should include their max
if (i2 == 0 && (type == MONTH || type == DAY_OF_WEEK || type == DAY_OF_MONTH) ) { if (i2 == 0 && (type == MONTH || type == DAY_OF_WEEK || type == DAY_OF_MONTH)) {
i2 = max; i2 = max;
} }
@ -1185,7 +1187,7 @@ public final class CronExpression implements Serializable, Cloneable {
while (!gotOne) { while (!gotOne) {
//if (endTime != null && cl.getTime().after(endTime)) return null; //if (endTime != null && cl.getTime().after(endTime)) return null;
if(cl.get(Calendar.YEAR) > 2999) { // prevent endless loop... if (cl.get(Calendar.YEAR) > 2999) { // prevent endless loop...
return null; return null;
} }
@ -1262,13 +1264,13 @@ public final class CronExpression implements Serializable, Cloneable {
if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule
st = daysOfMonth.tailSet(day); st = daysOfMonth.tailSet(day);
if (lastdayOfMonth) { if (lastdayOfMonth) {
if(!nearestWeekday) { if (!nearestWeekday) {
t = day; t = day;
day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
day -= lastdayOffset; day -= lastdayOffset;
if(t > day) { if (t > day) {
mon++; mon++;
if(mon > 12) { if (mon > 12) {
mon = 1; mon = 1;
tmon = 3333; // ensure test of mon != tmon further below fails tmon = 3333; // ensure test of mon != tmon further below fails
cl.add(Calendar.YEAR, 1); cl.add(Calendar.YEAR, 1);
@ -1280,7 +1282,7 @@ public final class CronExpression implements Serializable, Cloneable {
day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
day -= lastdayOffset; day -= lastdayOffset;
java.util.Calendar tcal = java.util.Calendar.getInstance(getTimeZone()); Calendar tcal = Calendar.getInstance(getTimeZone());
tcal.set(Calendar.SECOND, 0); tcal.set(Calendar.SECOND, 0);
tcal.set(Calendar.MINUTE, 0); tcal.set(Calendar.MINUTE, 0);
tcal.set(Calendar.HOUR_OF_DAY, 0); tcal.set(Calendar.HOUR_OF_DAY, 0);
@ -1291,13 +1293,13 @@ public final class CronExpression implements Serializable, Cloneable {
int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
int dow = tcal.get(Calendar.DAY_OF_WEEK); int dow = tcal.get(Calendar.DAY_OF_WEEK);
if(dow == Calendar.SATURDAY && day == 1) { if (dow == Calendar.SATURDAY && day == 1) {
day += 2; day += 2;
} else if(dow == Calendar.SATURDAY) { } else if (dow == Calendar.SATURDAY) {
day -= 1; day -= 1;
} else if(dow == Calendar.SUNDAY && day == ldom) { } else if (dow == Calendar.SUNDAY && day == ldom) {
day -= 2; day -= 2;
} else if(dow == Calendar.SUNDAY) { } else if (dow == Calendar.SUNDAY) {
day += 1; day += 1;
} }
@ -1307,16 +1309,16 @@ public final class CronExpression implements Serializable, Cloneable {
tcal.set(Calendar.DAY_OF_MONTH, day); tcal.set(Calendar.DAY_OF_MONTH, day);
tcal.set(Calendar.MONTH, mon - 1); tcal.set(Calendar.MONTH, mon - 1);
Date nTime = tcal.getTime(); Date nTime = tcal.getTime();
if(nTime.before(afterTime)) { if (nTime.before(afterTime)) {
day = 1; day = 1;
mon++; mon++;
} }
} }
} else if(nearestWeekday) { } else if (nearestWeekday) {
t = day; t = day;
day = daysOfMonth.first(); day = daysOfMonth.first();
java.util.Calendar tcal = java.util.Calendar.getInstance(getTimeZone()); Calendar tcal = Calendar.getInstance(getTimeZone());
tcal.set(Calendar.SECOND, 0); tcal.set(Calendar.SECOND, 0);
tcal.set(Calendar.MINUTE, 0); tcal.set(Calendar.MINUTE, 0);
tcal.set(Calendar.HOUR_OF_DAY, 0); tcal.set(Calendar.HOUR_OF_DAY, 0);
@ -1327,13 +1329,13 @@ public final class CronExpression implements Serializable, Cloneable {
int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
int dow = tcal.get(Calendar.DAY_OF_WEEK); int dow = tcal.get(Calendar.DAY_OF_WEEK);
if(dow == Calendar.SATURDAY && day == 1) { if (dow == Calendar.SATURDAY && day == 1) {
day += 2; day += 2;
} else if(dow == Calendar.SATURDAY) { } else if (dow == Calendar.SATURDAY) {
day -= 1; day -= 1;
} else if(dow == Calendar.SUNDAY && day == ldom) { } else if (dow == Calendar.SUNDAY && day == ldom) {
day -= 2; day -= 2;
} else if(dow == Calendar.SUNDAY) { } else if (dow == Calendar.SUNDAY) {
day += 1; day += 1;
} }
@ -1344,7 +1346,7 @@ public final class CronExpression implements Serializable, Cloneable {
tcal.set(Calendar.DAY_OF_MONTH, day); tcal.set(Calendar.DAY_OF_MONTH, day);
tcal.set(Calendar.MONTH, mon - 1); tcal.set(Calendar.MONTH, mon - 1);
Date nTime = tcal.getTime(); Date nTime = tcal.getTime();
if(nTime.before(afterTime)) { if (nTime.before(afterTime)) {
day = daysOfMonth.first(); day = daysOfMonth.first();
mon++; mon++;
} }
@ -1442,8 +1444,8 @@ public final class CronExpression implements Serializable, Cloneable {
daysToAdd = (nthdayOfWeek - weekOfMonth) * 7; daysToAdd = (nthdayOfWeek - weekOfMonth) * 7;
day += daysToAdd; day += daysToAdd;
if (daysToAdd < 0 if (daysToAdd < 0
|| day > getLastDayOfMonth(mon, cl || day > getLastDayOfMonth(mon, cl
.get(Calendar.YEAR))) { .get(Calendar.YEAR))) {
cl.set(Calendar.SECOND, 0); cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0); cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0); cl.set(Calendar.HOUR_OF_DAY, 0);
@ -1501,7 +1503,7 @@ public final class CronExpression implements Serializable, Cloneable {
} }
} else { // dayOfWSpec && !dayOfMSpec } else { // dayOfWSpec && !dayOfMSpec
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"Support for specifying both a day-of-week AND a day-of-month parameter is not implemented."); "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.");
} }
cl.set(Calendar.DAY_OF_MONTH, day); cl.set(Calendar.DAY_OF_MONTH, day);
@ -1576,13 +1578,13 @@ public final class CronExpression implements Serializable, Cloneable {
* Advance the calendar to the particular hour paying particular attention * Advance the calendar to the particular hour paying particular attention
* to daylight saving problems. * to daylight saving problems.
* *
* @param cal the calendar to operate on * @param cal the calendar to operate on
* @param hour the hour to set * @param hour the hour to set
*/ */
protected void setCalendarHour(Calendar cal, int hour) { protected void setCalendarHour(Calendar cal, int hour) {
cal.set(java.util.Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.HOUR_OF_DAY, hour);
if (cal.get(java.util.Calendar.HOUR_OF_DAY) != hour && hour != 24) { if (cal.get(Calendar.HOUR_OF_DAY) != hour && hour != 24) {
cal.set(java.util.Calendar.HOUR_OF_DAY, hour + 1); cal.set(Calendar.HOUR_OF_DAY, hour + 1);
} }
} }
@ -1637,7 +1639,7 @@ public final class CronExpression implements Serializable, Cloneable {
return 31; return 31;
default: default:
throw new IllegalArgumentException("Illegal month number: " throw new IllegalArgumentException("Illegal month number: "
+ monthNum); + monthNum);
} }
} }

View File

@ -7,6 +7,7 @@ public class XxlJobException extends RuntimeException {
public XxlJobException() { public XxlJobException() {
} }
public XxlJobException(String message) { public XxlJobException(String message) {
super(message); super(message);
} }

View File

@ -19,8 +19,9 @@ public class XxlJobGroup {
// registry list // registry list
private List<String> registryList; // 执行器地址列表(系统注册) private List<String> registryList; // 执行器地址列表(系统注册)
public List<String> getRegistryList() { public List<String> getRegistryList() {
if (addressList!=null && addressList.trim().length()>0) { if (addressList != null && addressList.trim().length() > 0) {
registryList = new ArrayList<String>(Arrays.asList(addressList.split(","))); registryList = new ArrayList<String>(Arrays.asList(addressList.split(",")));
} }
return registryList; return registryList;

View File

@ -9,229 +9,229 @@ import java.util.Date;
*/ */
public class XxlJobInfo { public class XxlJobInfo {
private int id; // 主键ID private int id; // 主键ID
private int jobGroup; // 执行器主键ID private int jobGroup; // 执行器主键ID
private String jobDesc; private String jobDesc;
private Date addTime; private Date addTime;
private Date updateTime; private Date updateTime;
private String author; // 负责人 private String author; // 负责人
private String alarmEmail; // 报警邮件 private String alarmEmail; // 报警邮件
private String scheduleType; // 调度类型 private String scheduleType; // 调度类型
private String scheduleConf; // 调度配置,值含义取决于调度类型 private String scheduleConf; // 调度配置,值含义取决于调度类型
private String misfireStrategy; // 调度过期策略 private String misfireStrategy; // 调度过期策略
private String executorRouteStrategy; // 执行器路由策略 private String executorRouteStrategy; // 执行器路由策略
private String executorHandler; // 执行器任务Handler名称 private String executorHandler; // 执行器任务Handler名称
private String executorParam; // 执行器,任务参数 private String executorParam; // 执行器,任务参数
private String executorBlockStrategy; // 阻塞处理策略 private String executorBlockStrategy; // 阻塞处理策略
private int executorTimeout; // 任务执行超时时间,单位秒 private int executorTimeout; // 任务执行超时时间,单位秒
private int executorFailRetryCount; // 失败重试次数 private int executorFailRetryCount; // 失败重试次数
private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum
private String glueSource; // GLUE源代码 private String glueSource; // GLUE源代码
private String glueRemark; // GLUE备注 private String glueRemark; // GLUE备注
private Date glueUpdatetime; // GLUE更新时间 private Date glueUpdatetime; // GLUE更新时间
private String childJobId; // 子任务ID多个逗号分隔 private String childJobId; // 子任务ID多个逗号分隔
private int triggerStatus; // 调度状态0-停止1-运行 private int triggerStatus; // 调度状态0-停止1-运行
private long triggerLastTime; // 上次调度时间 private long triggerLastTime; // 上次调度时间
private long triggerNextTime; // 下次调度时间 private long triggerNextTime; // 下次调度时间
public int getId() { public int getId() {
return id; return id;
} }
public void setId(int id) { public void setId(int id) {
this.id = id; this.id = id;
} }
public int getJobGroup() { public int getJobGroup() {
return jobGroup; return jobGroup;
} }
public void setJobGroup(int jobGroup) { public void setJobGroup(int jobGroup) {
this.jobGroup = jobGroup; this.jobGroup = jobGroup;
} }
public String getJobDesc() { public String getJobDesc() {
return jobDesc; return jobDesc;
} }
public void setJobDesc(String jobDesc) { public void setJobDesc(String jobDesc) {
this.jobDesc = jobDesc; this.jobDesc = jobDesc;
} }
public Date getAddTime() { public Date getAddTime() {
return addTime; return addTime;
} }
public void setAddTime(Date addTime) { public void setAddTime(Date addTime) {
this.addTime = addTime; this.addTime = addTime;
} }
public Date getUpdateTime() { public Date getUpdateTime() {
return updateTime; return updateTime;
} }
public void setUpdateTime(Date updateTime) { public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime; this.updateTime = updateTime;
} }
public String getAuthor() { public String getAuthor() {
return author; return author;
} }
public void setAuthor(String author) { public void setAuthor(String author) {
this.author = author; this.author = author;
} }
public String getAlarmEmail() { public String getAlarmEmail() {
return alarmEmail; return alarmEmail;
} }
public void setAlarmEmail(String alarmEmail) { public void setAlarmEmail(String alarmEmail) {
this.alarmEmail = alarmEmail; this.alarmEmail = alarmEmail;
} }
public String getScheduleType() { public String getScheduleType() {
return scheduleType; return scheduleType;
} }
public void setScheduleType(String scheduleType) { public void setScheduleType(String scheduleType) {
this.scheduleType = scheduleType; this.scheduleType = scheduleType;
} }
public String getScheduleConf() { public String getScheduleConf() {
return scheduleConf; return scheduleConf;
} }
public void setScheduleConf(String scheduleConf) { public void setScheduleConf(String scheduleConf) {
this.scheduleConf = scheduleConf; this.scheduleConf = scheduleConf;
} }
public String getMisfireStrategy() { public String getMisfireStrategy() {
return misfireStrategy; return misfireStrategy;
} }
public void setMisfireStrategy(String misfireStrategy) { public void setMisfireStrategy(String misfireStrategy) {
this.misfireStrategy = misfireStrategy; this.misfireStrategy = misfireStrategy;
} }
public String getExecutorRouteStrategy() { public String getExecutorRouteStrategy() {
return executorRouteStrategy; return executorRouteStrategy;
} }
public void setExecutorRouteStrategy(String executorRouteStrategy) { public void setExecutorRouteStrategy(String executorRouteStrategy) {
this.executorRouteStrategy = executorRouteStrategy; this.executorRouteStrategy = executorRouteStrategy;
} }
public String getExecutorHandler() { public String getExecutorHandler() {
return executorHandler; return executorHandler;
} }
public void setExecutorHandler(String executorHandler) { public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler; this.executorHandler = executorHandler;
} }
public String getExecutorParam() { public String getExecutorParam() {
return executorParam; return executorParam;
} }
public void setExecutorParam(String executorParam) { public void setExecutorParam(String executorParam) {
this.executorParam = executorParam; this.executorParam = executorParam;
} }
public String getExecutorBlockStrategy() { public String getExecutorBlockStrategy() {
return executorBlockStrategy; return executorBlockStrategy;
} }
public void setExecutorBlockStrategy(String executorBlockStrategy) { public void setExecutorBlockStrategy(String executorBlockStrategy) {
this.executorBlockStrategy = executorBlockStrategy; this.executorBlockStrategy = executorBlockStrategy;
} }
public int getExecutorTimeout() { public int getExecutorTimeout() {
return executorTimeout; return executorTimeout;
} }
public void setExecutorTimeout(int executorTimeout) { public void setExecutorTimeout(int executorTimeout) {
this.executorTimeout = executorTimeout; this.executorTimeout = executorTimeout;
} }
public int getExecutorFailRetryCount() { public int getExecutorFailRetryCount() {
return executorFailRetryCount; return executorFailRetryCount;
} }
public void setExecutorFailRetryCount(int executorFailRetryCount) { public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount; this.executorFailRetryCount = executorFailRetryCount;
} }
public String getGlueType() { public String getGlueType() {
return glueType; return glueType;
} }
public void setGlueType(String glueType) { public void setGlueType(String glueType) {
this.glueType = glueType; this.glueType = glueType;
} }
public String getGlueSource() { public String getGlueSource() {
return glueSource; return glueSource;
} }
public void setGlueSource(String glueSource) { public void setGlueSource(String glueSource) {
this.glueSource = glueSource; this.glueSource = glueSource;
} }
public String getGlueRemark() { public String getGlueRemark() {
return glueRemark; return glueRemark;
} }
public void setGlueRemark(String glueRemark) { public void setGlueRemark(String glueRemark) {
this.glueRemark = glueRemark; this.glueRemark = glueRemark;
} }
public Date getGlueUpdatetime() { public Date getGlueUpdatetime() {
return glueUpdatetime; return glueUpdatetime;
} }
public void setGlueUpdatetime(Date glueUpdatetime) { public void setGlueUpdatetime(Date glueUpdatetime) {
this.glueUpdatetime = glueUpdatetime; this.glueUpdatetime = glueUpdatetime;
} }
public String getChildJobId() { public String getChildJobId() {
return childJobId; return childJobId;
} }
public void setChildJobId(String childJobId) { public void setChildJobId(String childJobId) {
this.childJobId = childJobId; this.childJobId = childJobId;
} }
public int getTriggerStatus() { public int getTriggerStatus() {
return triggerStatus; return triggerStatus;
} }
public void setTriggerStatus(int triggerStatus) { public void setTriggerStatus(int triggerStatus) {
this.triggerStatus = triggerStatus; this.triggerStatus = triggerStatus;
} }
public long getTriggerLastTime() { public long getTriggerLastTime() {
return triggerLastTime; return triggerLastTime;
} }
public void setTriggerLastTime(long triggerLastTime) { public void setTriggerLastTime(long triggerLastTime) {
this.triggerLastTime = triggerLastTime; this.triggerLastTime = triggerLastTime;
} }
public long getTriggerNextTime() { public long getTriggerNextTime() {
return triggerNextTime; return triggerNextTime;
} }
public void setTriggerNextTime(long triggerNextTime) { public void setTriggerNextTime(long triggerNextTime) {
this.triggerNextTime = triggerNextTime; this.triggerNextTime = triggerNextTime;
} }
} }

View File

@ -4,154 +4,155 @@ import java.util.Date;
/** /**
* xxl-job log, used to track trigger process * xxl-job log, used to track trigger process
*
* @author xuxueli 2015-12-19 23:19:09 * @author xuxueli 2015-12-19 23:19:09
*/ */
public class XxlJobLog { public class XxlJobLog {
private long id; private long id;
// job info // job info
private int jobGroup; private int jobGroup;
private int jobId; private int jobId;
// execute info // execute info
private String executorAddress; private String executorAddress;
private String executorHandler; private String executorHandler;
private String executorParam; private String executorParam;
private String executorShardingParam; private String executorShardingParam;
private int executorFailRetryCount; private int executorFailRetryCount;
// trigger info // trigger info
private Date triggerTime; private Date triggerTime;
private int triggerCode; private int triggerCode;
private String triggerMsg; private String triggerMsg;
// handle info // handle info
private Date handleTime; private Date handleTime;
private int handleCode; private int handleCode;
private String handleMsg; private String handleMsg;
// alarm info // alarm info
private int alarmStatus; private int alarmStatus;
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public int getJobGroup() { public int getJobGroup() {
return jobGroup; return jobGroup;
} }
public void setJobGroup(int jobGroup) { public void setJobGroup(int jobGroup) {
this.jobGroup = jobGroup; this.jobGroup = jobGroup;
} }
public int getJobId() { public int getJobId() {
return jobId; return jobId;
} }
public void setJobId(int jobId) { public void setJobId(int jobId) {
this.jobId = jobId; this.jobId = jobId;
} }
public String getExecutorAddress() { public String getExecutorAddress() {
return executorAddress; return executorAddress;
} }
public void setExecutorAddress(String executorAddress) { public void setExecutorAddress(String executorAddress) {
this.executorAddress = executorAddress; this.executorAddress = executorAddress;
} }
public String getExecutorHandler() { public String getExecutorHandler() {
return executorHandler; return executorHandler;
} }
public void setExecutorHandler(String executorHandler) { public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler; this.executorHandler = executorHandler;
} }
public String getExecutorParam() { public String getExecutorParam() {
return executorParam; return executorParam;
} }
public void setExecutorParam(String executorParam) { public void setExecutorParam(String executorParam) {
this.executorParam = executorParam; this.executorParam = executorParam;
} }
public String getExecutorShardingParam() { public String getExecutorShardingParam() {
return executorShardingParam; return executorShardingParam;
} }
public void setExecutorShardingParam(String executorShardingParam) { public void setExecutorShardingParam(String executorShardingParam) {
this.executorShardingParam = executorShardingParam; this.executorShardingParam = executorShardingParam;
} }
public int getExecutorFailRetryCount() { public int getExecutorFailRetryCount() {
return executorFailRetryCount; return executorFailRetryCount;
} }
public void setExecutorFailRetryCount(int executorFailRetryCount) { public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount; this.executorFailRetryCount = executorFailRetryCount;
} }
public Date getTriggerTime() { public Date getTriggerTime() {
return triggerTime; return triggerTime;
} }
public void setTriggerTime(Date triggerTime) { public void setTriggerTime(Date triggerTime) {
this.triggerTime = triggerTime; this.triggerTime = triggerTime;
} }
public int getTriggerCode() { public int getTriggerCode() {
return triggerCode; return triggerCode;
} }
public void setTriggerCode(int triggerCode) { public void setTriggerCode(int triggerCode) {
this.triggerCode = triggerCode; this.triggerCode = triggerCode;
} }
public String getTriggerMsg() { public String getTriggerMsg() {
return triggerMsg; return triggerMsg;
} }
public void setTriggerMsg(String triggerMsg) { public void setTriggerMsg(String triggerMsg) {
this.triggerMsg = triggerMsg; this.triggerMsg = triggerMsg;
} }
public Date getHandleTime() { public Date getHandleTime() {
return handleTime; return handleTime;
} }
public void setHandleTime(Date handleTime) { public void setHandleTime(Date handleTime) {
this.handleTime = handleTime; this.handleTime = handleTime;
} }
public int getHandleCode() { public int getHandleCode() {
return handleCode; return handleCode;
} }
public void setHandleCode(int handleCode) { public void setHandleCode(int handleCode) {
this.handleCode = handleCode; this.handleCode = handleCode;
} }
public String getHandleMsg() { public String getHandleMsg() {
return handleMsg; return handleMsg;
} }
public void setHandleMsg(String handleMsg) { public void setHandleMsg(String handleMsg) {
this.handleMsg = handleMsg; this.handleMsg = handleMsg;
} }
public int getAlarmStatus() { public int getAlarmStatus() {
return alarmStatus; return alarmStatus;
} }
public void setAlarmStatus(int alarmStatus) { public void setAlarmStatus(int alarmStatus) {
this.alarmStatus = alarmStatus; this.alarmStatus = alarmStatus;
} }
} }

View File

@ -4,72 +4,73 @@ import java.util.Date;
/** /**
* xxl-job log for glue, used to track job code process * xxl-job log for glue, used to track job code process
*
* @author xuxueli 2016-5-19 17:57:46 * @author xuxueli 2016-5-19 17:57:46
*/ */
public class XxlJobLogGlue { public class XxlJobLogGlue {
private int id; private int id;
private int jobId; // 任务主键ID private int jobId; // 任务主键ID
private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum
private String glueSource; private String glueSource;
private String glueRemark; private String glueRemark;
private Date addTime; private Date addTime;
private Date updateTime; private Date updateTime;
public int getId() { public int getId() {
return id; return id;
} }
public void setId(int id) { public void setId(int id) {
this.id = id; this.id = id;
} }
public int getJobId() { public int getJobId() {
return jobId; return jobId;
} }
public void setJobId(int jobId) { public void setJobId(int jobId) {
this.jobId = jobId; this.jobId = jobId;
} }
public String getGlueType() { public String getGlueType() {
return glueType; return glueType;
} }
public void setGlueType(String glueType) { public void setGlueType(String glueType) {
this.glueType = glueType; this.glueType = glueType;
} }
public String getGlueSource() { public String getGlueSource() {
return glueSource; return glueSource;
} }
public void setGlueSource(String glueSource) { public void setGlueSource(String glueSource) {
this.glueSource = glueSource; this.glueSource = glueSource;
} }
public String getGlueRemark() { public String getGlueRemark() {
return glueRemark; return glueRemark;
} }
public void setGlueRemark(String glueRemark) { public void setGlueRemark(String glueRemark) {
this.glueRemark = glueRemark; this.glueRemark = glueRemark;
} }
public Date getAddTime() { public Date getAddTime() {
return addTime; return addTime;
} }
public void setAddTime(Date addTime) { public void setAddTime(Date addTime) {
this.addTime = addTime; this.addTime = addTime;
} }
public Date getUpdateTime() { public Date getUpdateTime() {
return updateTime; return updateTime;
} }
public void setUpdateTime(Date updateTime) { public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime; this.updateTime = updateTime;
} }
} }

View File

@ -7,67 +7,67 @@ import org.springframework.util.StringUtils;
*/ */
public class XxlJobUser { public class XxlJobUser {
private int id; private int id;
private String username; // 账号 private String username; // 账号
private String password; // 密码 private String password; // 密码
private int role; // 角色0-普通用户、1-管理员 private int role; // 角色0-普通用户、1-管理员
private String permission; // 权限执行器ID列表多个逗号分割 private String permission; // 权限执行器ID列表多个逗号分割
public int getId() { public int getId() {
return id; return id;
} }
public void setId(int id) { public void setId(int id) {
this.id = id; this.id = id;
} }
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public int getRole() { public int getRole() {
return role; return role;
} }
public void setRole(int role) { public void setRole(int role) {
this.role = role; this.role = role;
} }
public String getPermission() { public String getPermission() {
return permission; return permission;
} }
public void setPermission(String permission) { public void setPermission(String permission) {
this.permission = permission; this.permission = permission;
} }
// plugin // plugin
public boolean validPermission(int jobGroup){ public boolean validPermission(int jobGroup) {
if (this.role == 1) { if (this.role == 1) {
return true; return true;
} else { } else {
if (StringUtils.hasText(this.permission)) { if (StringUtils.hasText(this.permission)) {
for (String permissionItem : this.permission.split(",")) { for (String permissionItem : this.permission.split(",")) {
if (String.valueOf(jobGroup).equals(permissionItem)) { if (String.valueOf(jobGroup).equals(permissionItem)) {
return true; return true;
} }
} }
} }
return false; return false;
} }
} }
} }

View File

@ -1,4 +1,4 @@
//package com.xxl.job.admin.core.jobbean; package com.xxl.job.admin.core.old;//package com.xxl.job.admin.core.jobbean;
// //
//import com.xxl.job.admin.core.thread.JobTriggerPoolHelper; //import com.xxl.job.admin.core.thread.JobTriggerPoolHelper;
//import com.xxl.job.admin.core.trigger.TriggerTypeEnum; //import com.xxl.job.admin.core.trigger.TriggerTypeEnum;

View File

@ -1,4 +1,4 @@
//package com.xxl.job.admin.core.schedule; package com.xxl.job.admin.core.old;//package com.xxl.job.admin.core.schedule;
// //
//import com.xxl.job.admin.core.conf.XxlJobAdminConfig; //import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
//import com.xxl.job.admin.core.jobbean.RemoteHttpJobBean; //import com.xxl.job.admin.core.jobbean.RemoteHttpJobBean;

View File

@ -1,4 +1,4 @@
//package com.xxl.job.admin.core.quartz; package com.xxl.job.admin.core.old;//package com.xxl.job.admin.core.quartz;
// //
//import org.quartz.SchedulerConfigException; //import org.quartz.SchedulerConfigException;
//import org.quartz.spi.ThreadPool; //import org.quartz.spi.ThreadPool;

View File

@ -30,13 +30,14 @@ public enum ExecutorRouteStrategyEnum {
public String getTitle() { public String getTitle() {
return title; return title;
} }
public ExecutorRouter getRouter() { public ExecutorRouter getRouter() {
return router; return router;
} }
public static ExecutorRouteStrategyEnum match(String name, ExecutorRouteStrategyEnum defaultItem){ public static ExecutorRouteStrategyEnum match(String name, ExecutorRouteStrategyEnum defaultItem) {
if (name != null) { if (name != null) {
for (ExecutorRouteStrategyEnum item: ExecutorRouteStrategyEnum.values()) { for (ExecutorRouteStrategyEnum item : ExecutorRouteStrategyEnum.values()) {
if (item.name().equals(name)) { if (item.name().equals(name)) {
return item; return item;
} }

View File

@ -17,7 +17,7 @@ public abstract class ExecutorRouter {
* route address * route address
* *
* @param addressList * @param addressList
* @return ReturnT.content=address * @return ReturnT.content=address
*/ */
public abstract ReturnT<String> route(TriggerParam triggerParam, List<String> addressList); public abstract ReturnT<String> route(TriggerParam triggerParam, List<String> addressList);

View File

@ -1,7 +1,7 @@
package com.xxl.job.admin.core.route.strategy; package com.xxl.job.admin.core.route.strategy;
import com.xxl.job.admin.core.scheduler.XxlJobScheduler;
import com.xxl.job.admin.core.route.ExecutorRouter; import com.xxl.job.admin.core.route.ExecutorRouter;
import com.xxl.job.admin.core.scheduler.XxlJobScheduler;
import com.xxl.job.admin.core.util.I18nUtil; import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.ExecutorBiz; import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.model.IdleBeatParam; import com.xxl.job.core.biz.model.IdleBeatParam;
@ -26,13 +26,13 @@ public class ExecutorRouteBusyover extends ExecutorRouter {
idleBeatResult = executorBiz.idleBeat(new IdleBeatParam(triggerParam.getJobId())); idleBeatResult = executorBiz.idleBeat(new IdleBeatParam(triggerParam.getJobId()));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
idleBeatResult = new ReturnT<String>(ReturnT.FAIL_CODE, ""+e ); idleBeatResult = new ReturnT<String>(ReturnT.FAIL_CODE, "" + e);
} }
idleBeatResultSB.append( (idleBeatResultSB.length()>0)?"<br><br>":"") idleBeatResultSB.append((idleBeatResultSB.length() > 0) ? "<br><br>" : "")
.append(I18nUtil.getString("jobconf_idleBeat") + "") .append(I18nUtil.getString("jobconf_idleBeat") + "")
.append("<br>address").append(address) .append("<br>address").append(address)
.append("<br>code").append(idleBeatResult.getCode()) .append("<br>code").append(idleBeatResult.getCode())
.append("<br>msg").append(idleBeatResult.getMsg()); .append("<br>msg").append(idleBeatResult.getMsg());
// beat success // beat success
if (idleBeatResult.getCode() == ReturnT.SUCCESS_CODE) { if (idleBeatResult.getCode() == ReturnT.SUCCESS_CODE) {

View File

@ -13,8 +13,8 @@ import java.util.TreeMap;
/** /**
* JOBJOBJOB * JOBJOBJOB
* avirtual node * avirtual node
* bhash method replace hashCodeStringhashCodehashCode * bhash method replace hashCodeStringhashCodehashCode
* Created by xuxueli on 17/3/10. * Created by xuxueli on 17/3/10.
*/ */
public class ExecutorRouteConsistentHash extends ExecutorRouter { public class ExecutorRouteConsistentHash extends ExecutorRouter {
@ -23,6 +23,7 @@ public class ExecutorRouteConsistentHash extends ExecutorRouter {
/** /**
* get hash code on 2^32 ring (md5hash) * get hash code on 2^32 ring (md5hash)
*
* @param key * @param key
* @return * @return
*/ */
@ -48,9 +49,9 @@ public class ExecutorRouteConsistentHash extends ExecutorRouter {
// hash code, Truncate to 32-bits // hash code, Truncate to 32-bits
long hashCode = ((long) (digest[3] & 0xFF) << 24) long hashCode = ((long) (digest[3] & 0xFF) << 24)
| ((long) (digest[2] & 0xFF) << 16) | ((long) (digest[2] & 0xFF) << 16)
| ((long) (digest[1] & 0xFF) << 8) | ((long) (digest[1] & 0xFF) << 8)
| (digest[0] & 0xFF); | (digest[0] & 0xFF);
long truncateHashCode = hashCode & 0xffffffffL; long truncateHashCode = hashCode & 0xffffffffL;
return truncateHashCode; return truncateHashCode;
@ -61,7 +62,7 @@ public class ExecutorRouteConsistentHash extends ExecutorRouter {
// ------A1------A2-------A3------ // ------A1------A2-------A3------
// -----------J1------------------ // -----------J1------------------
TreeMap<Long, String> addressRing = new TreeMap<Long, String>(); TreeMap<Long, String> addressRing = new TreeMap<Long, String>();
for (String address: addressList) { for (String address : addressList) {
for (int i = 0; i < VIRTUAL_NODE_NUM; i++) { for (int i = 0; i < VIRTUAL_NODE_NUM; i++) {
long addressHash = hash("SHARD-" + address + "-NODE-" + i); long addressHash = hash("SHARD-" + address + "-NODE-" + i);
addressRing.put(addressHash, address); addressRing.put(addressHash, address);

View File

@ -1,7 +1,7 @@
package com.xxl.job.admin.core.route.strategy; package com.xxl.job.admin.core.route.strategy;
import com.xxl.job.admin.core.scheduler.XxlJobScheduler;
import com.xxl.job.admin.core.route.ExecutorRouter; import com.xxl.job.admin.core.route.ExecutorRouter;
import com.xxl.job.admin.core.scheduler.XxlJobScheduler;
import com.xxl.job.admin.core.util.I18nUtil; import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.ExecutorBiz; import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.biz.model.ReturnT;
@ -26,13 +26,13 @@ public class ExecutorRouteFailover extends ExecutorRouter {
beatResult = executorBiz.beat(); beatResult = executorBiz.beat();
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
beatResult = new ReturnT<String>(ReturnT.FAIL_CODE, ""+e ); beatResult = new ReturnT<String>(ReturnT.FAIL_CODE, "" + e);
} }
beatResultSB.append( (beatResultSB.length()>0)?"<br><br>":"") beatResultSB.append((beatResultSB.length() > 0) ? "<br><br>" : "")
.append(I18nUtil.getString("jobconf_beat") + "") .append(I18nUtil.getString("jobconf_beat") + "")
.append("<br>address").append(address) .append("<br>address").append(address)
.append("<br>code").append(beatResult.getCode()) .append("<br>code").append(beatResult.getCode())
.append("<br>msg").append(beatResult.getMsg()); .append("<br>msg").append(beatResult.getMsg());
// beat success // beat success
if (beatResult.getCode() == ReturnT.SUCCESS_CODE) { if (beatResult.getCode() == ReturnT.SUCCESS_CODE) {

View File

@ -12,7 +12,7 @@ import java.util.List;
public class ExecutorRouteFirst extends ExecutorRouter { public class ExecutorRouteFirst extends ExecutorRouter {
@Override @Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList){ public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
return new ReturnT<String>(addressList.get(0)); return new ReturnT<String>(addressList.get(0));
} }

View File

@ -10,9 +10,9 @@ import java.util.concurrent.ConcurrentMap;
/** /**
* JOB使 * JOB使
* a(*)LFU(Least Frequently Used)使/ * a(*)LFU(Least Frequently Used)使/
* bLRU(Least Recently Used)使 * bLRU(Least Recently Used)使
* * <p>
* Created by xuxueli on 17/3/10. * Created by xuxueli on 17/3/10.
*/ */
public class ExecutorRouteLFU extends ExecutorRouter { public class ExecutorRouteLFU extends ExecutorRouter {
@ -25,7 +25,7 @@ public class ExecutorRouteLFU extends ExecutorRouter {
// cache clear // cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) { if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLfuMap.clear(); jobLfuMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24; CACHE_VALID_TIME = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
} }
// lfu item init // lfu item init
@ -36,20 +36,20 @@ public class ExecutorRouteLFU extends ExecutorRouter {
} }
// put new // put new
for (String address: addressList) { for (String address : addressList) {
if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) { if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) > 1000000) {
lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次缓解首次压力 lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次缓解首次压力
} }
} }
// remove old // remove old
List<String> delKeys = new ArrayList<>(); List<String> delKeys = new ArrayList<>();
for (String existKey: lfuItemMap.keySet()) { for (String existKey : lfuItemMap.keySet()) {
if (!addressList.contains(existKey)) { if (!addressList.contains(existKey)) {
delKeys.add(existKey); delKeys.add(existKey);
} }
} }
if (delKeys.size() > 0) { if (delKeys.size() > 0) {
for (String delKey: delKeys) { for (String delKey : delKeys) {
lfuItemMap.remove(delKey); lfuItemMap.remove(delKey);
} }
} }

View File

@ -12,9 +12,9 @@ import java.util.concurrent.ConcurrentMap;
/** /**
* JOB使 * JOB使
* aLFU(Least Frequently Used)使/ * aLFU(Least Frequently Used)使/
* b(*)LRU(Least Recently Used)使 * b(*)LRU(Least Recently Used)使
* * <p>
* Created by xuxueli on 17/3/10. * Created by xuxueli on 17/3/10.
*/ */
public class ExecutorRouteLRU extends ExecutorRouter { public class ExecutorRouteLRU extends ExecutorRouter {
@ -27,7 +27,7 @@ public class ExecutorRouteLRU extends ExecutorRouter {
// cache clear // cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) { if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLRUMap.clear(); jobLRUMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24; CACHE_VALID_TIME = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
} }
// init lru // init lru
@ -43,20 +43,20 @@ public class ExecutorRouteLRU extends ExecutorRouter {
} }
// put new // put new
for (String address: addressList) { for (String address : addressList) {
if (!lruItem.containsKey(address)) { if (!lruItem.containsKey(address)) {
lruItem.put(address, address); lruItem.put(address, address);
} }
} }
// remove old // remove old
List<String> delKeys = new ArrayList<>(); List<String> delKeys = new ArrayList<>();
for (String existKey: lruItem.keySet()) { for (String existKey : lruItem.keySet()) {
if (!addressList.contains(existKey)) { if (!addressList.contains(existKey)) {
delKeys.add(existKey); delKeys.add(existKey);
} }
} }
if (delKeys.size() > 0) { if (delKeys.size() > 0) {
for (String delKey: delKeys) { for (String delKey : delKeys) {
lruItem.remove(delKey); lruItem.remove(delKey);
} }
} }

View File

@ -13,7 +13,7 @@ public class ExecutorRouteLast extends ExecutorRouter {
@Override @Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) { public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
return new ReturnT<String>(addressList.get(addressList.size()-1)); return new ReturnT<String>(addressList.get(addressList.size() - 1));
} }
} }

View File

@ -22,7 +22,7 @@ public class ExecutorRouteRound extends ExecutorRouter {
// cache clear // cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) { if (System.currentTimeMillis() > CACHE_VALID_TIME) {
routeCountEachJob.clear(); routeCountEachJob.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24; CACHE_VALID_TIME = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
} }
AtomicInteger count = routeCountEachJob.get(jobId); AtomicInteger count = routeCountEachJob.get(jobId);
@ -39,7 +39,7 @@ public class ExecutorRouteRound extends ExecutorRouter {
@Override @Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) { public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
String address = addressList.get(count(triggerParam.getJobId())%addressList.size()); String address = addressList.get(count(triggerParam.getJobId()) % addressList.size());
return new ReturnT<String>(address); return new ReturnT<String>(address);
} }

View File

@ -27,8 +27,8 @@ public enum MisfireStrategyEnum {
return title; return title;
} }
public static MisfireStrategyEnum match(String name, MisfireStrategyEnum defaultItem){ public static MisfireStrategyEnum match(String name, MisfireStrategyEnum defaultItem) {
for (MisfireStrategyEnum item: MisfireStrategyEnum.values()) { for (MisfireStrategyEnum item : MisfireStrategyEnum.values()) {
if (item.name().equals(name)) { if (item.name().equals(name)) {
return item; return item;
} }

View File

@ -34,8 +34,8 @@ public enum ScheduleTypeEnum {
return title; return title;
} }
public static ScheduleTypeEnum match(String name, ScheduleTypeEnum defaultItem){ public static ScheduleTypeEnum match(String name, ScheduleTypeEnum defaultItem) {
for (ScheduleTypeEnum item: ScheduleTypeEnum.values()) { for (ScheduleTypeEnum item : ScheduleTypeEnum.values()) {
if (item.name().equals(name)) { if (item.name().equals(name)) {
return item; return item;
} }

View File

@ -16,7 +16,7 @@ import java.util.concurrent.ConcurrentMap;
* @author xuxueli 2018-10-28 00:18:17 * @author xuxueli 2018-10-28 00:18:17
*/ */
public class XxlJobScheduler { public class XxlJobScheduler {
private static final Logger logger = LoggerFactory.getLogger(XxlJobScheduler.class); private static final Logger logger = LoggerFactory.getLogger(XxlJobScheduler.class);
@ -70,17 +70,18 @@ public class XxlJobScheduler {
// ---------------------- I18n ---------------------- // ---------------------- I18n ----------------------
private void initI18n(){ private void initI18n() {
for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) { for (ExecutorBlockStrategyEnum item : ExecutorBlockStrategyEnum.values()) {
item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name()))); item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name())));
} }
} }
// ---------------------- executor-client ---------------------- // ---------------------- executor-client ----------------------
private static ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<String, ExecutorBiz>(); private static ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<String, ExecutorBiz>();
public static ExecutorBiz getExecutorBiz(String address) throws Exception { public static ExecutorBiz getExecutorBiz(String address) throws Exception {
// valid // valid
if (address==null || address.trim().length()==0) { if (address == null || address.trim().length() == 0) {
return null; return null;
} }

View File

@ -20,83 +20,85 @@ import java.util.concurrent.*;
* @author xuxueli 2015-9-1 18:05:56 * @author xuxueli 2015-9-1 18:05:56
*/ */
public class JobCompleteHelper { public class JobCompleteHelper {
private static Logger logger = LoggerFactory.getLogger(JobCompleteHelper.class); private static Logger logger = LoggerFactory.getLogger(JobCompleteHelper.class);
private static JobCompleteHelper instance = new JobCompleteHelper(); private static JobCompleteHelper instance = new JobCompleteHelper();
public static JobCompleteHelper getInstance(){
return instance;
}
// ---------------------- monitor ---------------------- public static JobCompleteHelper getInstance() {
return instance;
}
private ThreadPoolExecutor callbackThreadPool = null; // ---------------------- monitor ----------------------
private Thread monitorThread;
private volatile boolean toStop = false;
public void start(){
// for callback private ThreadPoolExecutor callbackThreadPool = null;
callbackThreadPool = new ThreadPoolExecutor( private Thread monitorThread;
2, private volatile boolean toStop = false;
20,
30L, public void start() {
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(3000), // for callback
new ThreadFactory() { callbackThreadPool = new ThreadPoolExecutor(
@Override 2,
public Thread newThread(Runnable r) { 20,
return new Thread(r, "xxl-job, admin JobLosedMonitorHelper-callbackThreadPool-" + r.hashCode()); 30L,
} TimeUnit.SECONDS,
}, new LinkedBlockingQueue<Runnable>(3000),
new RejectedExecutionHandler() { new ThreadFactory() {
@Override @Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { public Thread newThread(Runnable r) {
r.run(); return new Thread(r, "xxl-job, admin JobLosedMonitorHelper-callbackThreadPool-" + r.hashCode());
logger.warn(">>>>>>>>>>> xxl-job, callback too fast, match threadpool rejected handler(run now)."); }
} },
}); new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
r.run();
logger.warn(">>>>>>>>>>> xxl-job, callback too fast, match threadpool rejected handler(run now).");
}
});
// for monitor // for monitor
monitorThread = new Thread(new Runnable() { monitorThread = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
// wait for JobTriggerPoolHelper-init // wait for JobTriggerPoolHelper-init
try { try {
TimeUnit.MILLISECONDS.sleep(50); TimeUnit.MILLISECONDS.sleep(50);
} catch (InterruptedException e) { } catch (InterruptedException e) {
if (!toStop) { if (!toStop) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
} }
// monitor // monitor
while (!toStop) { while (!toStop) {
try { try {
// 任务结果丢失处理:调度记录停留在 "运行中" 状态超过10min且对应执行器心跳注册失败不在线则将本地调度主动标记失败 // 任务结果丢失处理:调度记录停留在 "运行中" 状态超过10min且对应执行器心跳注册失败不在线则将本地调度主动标记失败
Date losedTime = DateUtil.addMinutes(new Date(), -10); Date losedTime = DateUtil.addMinutes(new Date(), -10);
List<Long> losedJobIds = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findLostJobIds(losedTime); List<Long> losedJobIds = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findLostJobIds(losedTime);
if (losedJobIds!=null && losedJobIds.size()>0) { if (losedJobIds != null && losedJobIds.size() > 0) {
for (Long logId: losedJobIds) { for (Long logId : losedJobIds) {
XxlJobLog jobLog = new XxlJobLog(); XxlJobLog jobLog = new XxlJobLog();
jobLog.setId(logId); jobLog.setId(logId);
jobLog.setHandleTime(new Date()); jobLog.setHandleTime(new Date());
jobLog.setHandleCode(ReturnT.FAIL_CODE); jobLog.setHandleCode(ReturnT.FAIL_CODE);
jobLog.setHandleMsg( I18nUtil.getString("joblog_lost_fail") ); jobLog.setHandleMsg(I18nUtil.getString("joblog_lost_fail"));
XxlJobCompleter.updateHandleInfoAndFinish(jobLog); XxlJobCompleter.updateHandleInfoAndFinish(jobLog);
} }
} }
} catch (Exception e) { } catch (Exception e) {
if (!toStop) { if (!toStop) {
logger.error(">>>>>>>>>>> xxl-job, job fail monitor thread error:{}", e); logger.error(">>>>>>>>>>> xxl-job, job fail monitor thread error:{}", e);
} }
} }
try { try {
TimeUnit.SECONDS.sleep(60); TimeUnit.SECONDS.sleep(60);
@ -108,77 +110,76 @@ public class JobCompleteHelper {
} }
logger.info(">>>>>>>>>>> xxl-job, JobLosedMonitorHelper stop"); logger.info(">>>>>>>>>>> xxl-job, JobLosedMonitorHelper stop");
} }
}); });
monitorThread.setDaemon(true); monitorThread.setDaemon(true);
monitorThread.setName("xxl-job, admin JobLosedMonitorHelper"); monitorThread.setName("xxl-job, admin JobLosedMonitorHelper");
monitorThread.start(); monitorThread.start();
} }
public void toStop(){ public void toStop() {
toStop = true; toStop = true;
// stop registryOrRemoveThreadPool // stop registryOrRemoveThreadPool
callbackThreadPool.shutdownNow(); callbackThreadPool.shutdownNow();
// stop monitorThread (interrupt and wait) // stop monitorThread (interrupt and wait)
monitorThread.interrupt(); monitorThread.interrupt();
try { try {
monitorThread.join(); monitorThread.join();
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
} }
// ---------------------- helper ---------------------- // ---------------------- helper ----------------------
public ReturnT<String> callback(List<HandleCallbackParam> callbackParamList) { public ReturnT<String> callback(List<HandleCallbackParam> callbackParamList) {
callbackThreadPool.execute(new Runnable() { callbackThreadPool.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
for (HandleCallbackParam handleCallbackParam: callbackParamList) { for (HandleCallbackParam handleCallbackParam : callbackParamList) {
ReturnT<String> callbackResult = callback(handleCallbackParam); ReturnT<String> callbackResult = callback(handleCallbackParam);
logger.debug(">>>>>>>>> JobApiController.callback {}, handleCallbackParam={}, callbackResult={}", logger.debug(">>>>>>>>> JobApiController.callback {}, handleCallbackParam={}, callbackResult={}",
(callbackResult.getCode()== ReturnT.SUCCESS_CODE?"success":"fail"), handleCallbackParam, callbackResult); (callbackResult.getCode() == ReturnT.SUCCESS_CODE ? "success" : "fail"), handleCallbackParam, callbackResult);
} }
} }
}); });
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
private ReturnT<String> callback(HandleCallbackParam handleCallbackParam) { private ReturnT<String> callback(HandleCallbackParam handleCallbackParam) {
// valid log item // valid log item
XxlJobLog log = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().load(handleCallbackParam.getLogId()); XxlJobLog log = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().load(handleCallbackParam.getLogId());
if (log == null) { if (log == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "log item not found."); return new ReturnT<String>(ReturnT.FAIL_CODE, "log item not found.");
} }
if (log.getHandleCode() > 0) { if (log.getHandleCode() > 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "log repeate callback."); // avoid repeat callback, trigger child job etc return new ReturnT<String>(ReturnT.FAIL_CODE, "log repeate callback."); // avoid repeat callback, trigger child job etc
} }
// handle msg // handle msg
StringBuffer handleMsg = new StringBuffer(); StringBuffer handleMsg = new StringBuffer();
if (log.getHandleMsg()!=null) { if (log.getHandleMsg() != null) {
handleMsg.append(log.getHandleMsg()).append("<br>"); handleMsg.append(log.getHandleMsg()).append("<br>");
} }
if (handleCallbackParam.getHandleMsg() != null) { if (handleCallbackParam.getHandleMsg() != null) {
handleMsg.append(handleCallbackParam.getHandleMsg()); handleMsg.append(handleCallbackParam.getHandleMsg());
} }
// success, save log // success, save log
log.setHandleTime(new Date()); log.setHandleTime(new Date());
log.setHandleCode(handleCallbackParam.getHandleCode()); log.setHandleCode(handleCallbackParam.getHandleCode());
log.setHandleMsg(handleMsg.toString()); log.setHandleMsg(handleMsg.toString());
XxlJobCompleter.updateHandleInfoAndFinish(log); XxlJobCompleter.updateHandleInfoAndFinish(log);
return ReturnT.SUCCESS;
}
return ReturnT.SUCCESS;
}
} }

View File

@ -17,65 +17,67 @@ import java.util.concurrent.TimeUnit;
* @author xuxueli 2015-9-1 18:05:56 * @author xuxueli 2015-9-1 18:05:56
*/ */
public class JobFailMonitorHelper { public class JobFailMonitorHelper {
private static Logger logger = LoggerFactory.getLogger(JobFailMonitorHelper.class); private static Logger logger = LoggerFactory.getLogger(JobFailMonitorHelper.class);
private static JobFailMonitorHelper instance = new JobFailMonitorHelper(); private static JobFailMonitorHelper instance = new JobFailMonitorHelper();
public static JobFailMonitorHelper getInstance(){
return instance;
}
// ---------------------- monitor ---------------------- public static JobFailMonitorHelper getInstance() {
return instance;
}
private Thread monitorThread; // ---------------------- monitor ----------------------
private volatile boolean toStop = false;
public void start(){
monitorThread = new Thread(new Runnable() {
@Override private Thread monitorThread;
public void run() { private volatile boolean toStop = false;
// monitor public void start() {
while (!toStop) { monitorThread = new Thread(new Runnable() {
try {
List<Long> failLogIds = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findFailJobLogIds(1000); @Override
if (failLogIds!=null && !failLogIds.isEmpty()) { public void run() {
for (long failLogId: failLogIds) {
// lock log // monitor
int lockRet = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateAlarmStatus(failLogId, 0, -1); while (!toStop) {
if (lockRet < 1) { try {
continue;
}
XxlJobLog log = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().load(failLogId);
XxlJobInfo info = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(log.getJobId());
// 1、fail retry monitor List<Long> failLogIds = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findFailJobLogIds(1000);
if (log.getExecutorFailRetryCount() > 0) { if (failLogIds != null && !failLogIds.isEmpty()) {
JobTriggerPoolHelper.trigger(log.getJobId(), TriggerTypeEnum.RETRY, (log.getExecutorFailRetryCount()-1), log.getExecutorShardingParam(), log.getExecutorParam(), null); for (long failLogId : failLogIds) {
String retryMsg = "<br><br><span style=\"color:#F39C12;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_type_retry") +"<<<<<<<<<<< </span><br>";
log.setTriggerMsg(log.getTriggerMsg() + retryMsg);
XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateTriggerInfo(log);
}
// 2、fail alarm monitor // lock log
int newAlarmStatus = 0; // 告警状态0-默认、-1=锁定状态、1-无需告警、2-告警成功、3-告警失败 int lockRet = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateAlarmStatus(failLogId, 0, -1);
if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) { if (lockRet < 1) {
boolean alarmResult = XxlJobAdminConfig.getAdminConfig().getJobAlarmer().alarm(info, log); continue;
newAlarmStatus = alarmResult?2:3; }
} else { XxlJobLog log = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().load(failLogId);
newAlarmStatus = 1; XxlJobInfo info = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(log.getJobId());
}
XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateAlarmStatus(failLogId, -1, newAlarmStatus); // 1、fail retry monitor
} if (log.getExecutorFailRetryCount() > 0) {
} JobTriggerPoolHelper.trigger(log.getJobId(), TriggerTypeEnum.RETRY, (log.getExecutorFailRetryCount() - 1), log.getExecutorShardingParam(), log.getExecutorParam(), null);
String retryMsg = "<br><br><span style=\"color:#F39C12;\" > >>>>>>>>>>>" + I18nUtil.getString("jobconf_trigger_type_retry") + "<<<<<<<<<<< </span><br>";
log.setTriggerMsg(log.getTriggerMsg() + retryMsg);
XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateTriggerInfo(log);
}
} catch (Exception e) { // 2、fail alarm monitor
if (!toStop) { int newAlarmStatus = 0; // 告警状态0-默认、-1=锁定状态、1-无需告警、2-告警成功、3-告警失败
logger.error(">>>>>>>>>>> xxl-job, job fail monitor thread error:{}", e); if (info != null) {
} boolean alarmResult = XxlJobAdminConfig.getAdminConfig().getJobAlarmer().alarm(info, log);
} newAlarmStatus = alarmResult ? 2 : 3;
} else {
newAlarmStatus = 1;
}
XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateAlarmStatus(failLogId, -1, newAlarmStatus);
}
}
} catch (Exception e) {
if (!toStop) {
logger.error(">>>>>>>>>>> xxl-job, job fail monitor thread error:{}", e);
}
}
try { try {
TimeUnit.SECONDS.sleep(10); TimeUnit.SECONDS.sleep(10);
@ -87,24 +89,24 @@ public class JobFailMonitorHelper {
} }
logger.info(">>>>>>>>>>> xxl-job, job fail monitor thread stop"); logger.info(">>>>>>>>>>> xxl-job, job fail monitor thread stop");
} }
}); });
monitorThread.setDaemon(true); monitorThread.setDaemon(true);
monitorThread.setName("xxl-job, admin JobFailMonitorHelper"); monitorThread.setName("xxl-job, admin JobFailMonitorHelper");
monitorThread.start(); monitorThread.start();
} }
public void toStop(){ public void toStop() {
toStop = true; toStop = true;
// interrupt and wait // interrupt and wait
monitorThread.interrupt(); monitorThread.interrupt();
try { try {
monitorThread.join(); monitorThread.join();
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
} }
} }

View File

@ -20,14 +20,16 @@ public class JobLogReportHelper {
private static Logger logger = LoggerFactory.getLogger(JobLogReportHelper.class); private static Logger logger = LoggerFactory.getLogger(JobLogReportHelper.class);
private static JobLogReportHelper instance = new JobLogReportHelper(); private static JobLogReportHelper instance = new JobLogReportHelper();
public static JobLogReportHelper getInstance(){
public static JobLogReportHelper getInstance() {
return instance; return instance;
} }
private Thread logrThread; private Thread logrThread;
private volatile boolean toStop = false; private volatile boolean toStop = false;
public void start(){
public void start() {
logrThread = new Thread(new Runnable() { logrThread = new Thread(new Runnable() {
@Override @Override
@ -69,10 +71,10 @@ public class JobLogReportHelper {
xxlJobLogReport.setFailCount(0); xxlJobLogReport.setFailCount(0);
Map<String, Object> triggerCountMap = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findLogReport(todayFrom, todayTo); Map<String, Object> triggerCountMap = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findLogReport(todayFrom, todayTo);
if (triggerCountMap!=null && triggerCountMap.size()>0) { if (triggerCountMap != null && triggerCountMap.size() > 0) {
int triggerDayCount = triggerCountMap.containsKey("triggerDayCount")?Integer.valueOf(String.valueOf(triggerCountMap.get("triggerDayCount"))):0; int triggerDayCount = triggerCountMap.containsKey("triggerDayCount") ? Integer.valueOf(String.valueOf(triggerCountMap.get("triggerDayCount"))) : 0;
int triggerDayCountRunning = triggerCountMap.containsKey("triggerDayCountRunning")?Integer.valueOf(String.valueOf(triggerCountMap.get("triggerDayCountRunning"))):0; int triggerDayCountRunning = triggerCountMap.containsKey("triggerDayCountRunning") ? Integer.valueOf(String.valueOf(triggerCountMap.get("triggerDayCountRunning"))) : 0;
int triggerDayCountSuc = triggerCountMap.containsKey("triggerDayCountSuc")?Integer.valueOf(String.valueOf(triggerCountMap.get("triggerDayCountSuc"))):0; int triggerDayCountSuc = triggerCountMap.containsKey("triggerDayCountSuc") ? Integer.valueOf(String.valueOf(triggerCountMap.get("triggerDayCountSuc"))) : 0;
int triggerDayCountFail = triggerDayCount - triggerDayCountRunning - triggerDayCountSuc; int triggerDayCountFail = triggerDayCount - triggerDayCountRunning - triggerDayCountSuc;
xxlJobLogReport.setRunningCount(triggerDayCountRunning); xxlJobLogReport.setRunningCount(triggerDayCountRunning);
@ -94,8 +96,8 @@ public class JobLogReportHelper {
} }
// 2、log-clean: switch open & once each day // 2、log-clean: switch open & once each day
if (XxlJobAdminConfig.getAdminConfig().getLogretentiondays()>0 if (XxlJobAdminConfig.getAdminConfig().getLogretentiondays() > 0
&& System.currentTimeMillis() - lastCleanLogTime > 24*60*60*1000) { && System.currentTimeMillis() - lastCleanLogTime > 24 * 60 * 60 * 1000) {
// expire-time // expire-time
Calendar expiredDay = Calendar.getInstance(); Calendar expiredDay = Calendar.getInstance();
@ -110,10 +112,10 @@ public class JobLogReportHelper {
List<Long> logIds = null; List<Long> logIds = null;
do { do {
logIds = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findClearLogIds(0, 0, clearBeforeTime, 0, 1000); logIds = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findClearLogIds(0, 0, clearBeforeTime, 0, 1000);
if (logIds!=null && logIds.size()>0) { if (logIds != null && logIds.size() > 0) {
XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().clearLog(logIds); XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().clearLog(logIds);
} }
} while (logIds!=null && logIds.size()>0); } while (logIds != null && logIds.size() > 0);
// update clean time // update clean time
lastCleanLogTime = System.currentTimeMillis(); lastCleanLogTime = System.currentTimeMillis();
@ -138,7 +140,7 @@ public class JobLogReportHelper {
logrThread.start(); logrThread.start();
} }
public void toStop(){ public void toStop() {
toStop = true; toStop = true;
// interrupt and wait // interrupt and wait
logrThread.interrupt(); logrThread.interrupt();

View File

@ -15,190 +15,192 @@ import java.util.concurrent.*;
/** /**
* job registry instance * job registry instance
*
* @author xuxueli 2016-10-02 19:10:24 * @author xuxueli 2016-10-02 19:10:24
*/ */
public class JobRegistryHelper { public class JobRegistryHelper {
private static Logger logger = LoggerFactory.getLogger(JobRegistryHelper.class); private static Logger logger = LoggerFactory.getLogger(JobRegistryHelper.class);
private static JobRegistryHelper instance = new JobRegistryHelper(); private static JobRegistryHelper instance = new JobRegistryHelper();
public static JobRegistryHelper getInstance(){
return instance;
}
private ThreadPoolExecutor registryOrRemoveThreadPool = null; public static JobRegistryHelper getInstance() {
private Thread registryMonitorThread; return instance;
private volatile boolean toStop = false; }
public void start(){ private ThreadPoolExecutor registryOrRemoveThreadPool = null;
private Thread registryMonitorThread;
private volatile boolean toStop = false;
// for registry or remove public void start() {
registryOrRemoveThreadPool = new ThreadPoolExecutor(
2,
10,
30L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(2000),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "xxl-job, admin JobRegistryMonitorHelper-registryOrRemoveThreadPool-" + r.hashCode());
}
},
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
r.run();
logger.warn(">>>>>>>>>>> xxl-job, registry or remove too fast, match threadpool rejected handler(run now).");
}
});
// for monitor // for registry or remove
registryMonitorThread = new Thread(new Runnable() { registryOrRemoveThreadPool = new ThreadPoolExecutor(
@Override 2,
public void run() { 10,
while (!toStop) { 30L,
try { TimeUnit.SECONDS,
// auto registry group new LinkedBlockingQueue<Runnable>(2000),
List<XxlJobGroup> groupList = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().findByAddressType(0); new ThreadFactory() {
if (groupList!=null && !groupList.isEmpty()) { @Override
public Thread newThread(Runnable r) {
return new Thread(r, "xxl-job, admin JobRegistryMonitorHelper-registryOrRemoveThreadPool-" + r.hashCode());
}
},
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
r.run();
logger.warn(">>>>>>>>>>> xxl-job, registry or remove too fast, match threadpool rejected handler(run now).");
}
});
// remove dead address (admin/executor) // for monitor
List<Integer> ids = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().findDead(RegistryConfig.DEAD_TIMEOUT, new Date()); registryMonitorThread = new Thread(new Runnable() {
if (ids!=null && ids.size()>0) { @Override
XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().removeDead(ids); public void run() {
} while (!toStop) {
try {
// auto registry group
List<XxlJobGroup> groupList = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().findByAddressType(0);
if (groupList != null && !groupList.isEmpty()) {
// fresh online address (admin/executor) // remove dead address (admin/executor)
HashMap<String, List<String>> appAddressMap = new HashMap<String, List<String>>(); List<Integer> ids = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().findDead(RegistryConfig.DEAD_TIMEOUT, new Date());
List<XxlJobRegistry> list = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().findAll(RegistryConfig.DEAD_TIMEOUT, new Date()); if (ids != null && ids.size() > 0) {
if (list != null) { XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().removeDead(ids);
for (XxlJobRegistry item: list) { }
if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) {
String appname = item.getRegistryKey();
List<String> registryList = appAddressMap.get(appname);
if (registryList == null) {
registryList = new ArrayList<String>();
}
if (!registryList.contains(item.getRegistryValue())) { // fresh online address (admin/executor)
registryList.add(item.getRegistryValue()); HashMap<String, List<String>> appAddressMap = new HashMap<String, List<String>>();
} List<XxlJobRegistry> list = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().findAll(RegistryConfig.DEAD_TIMEOUT, new Date());
appAddressMap.put(appname, registryList); if (list != null) {
} for (XxlJobRegistry item : list) {
} if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) {
} String appname = item.getRegistryKey();
List<String> registryList = appAddressMap.get(appname);
if (registryList == null) {
registryList = new ArrayList<String>();
}
// fresh group address if (!registryList.contains(item.getRegistryValue())) {
for (XxlJobGroup group: groupList) { registryList.add(item.getRegistryValue());
List<String> registryList = appAddressMap.get(group.getAppname()); }
String addressListStr = null; appAddressMap.put(appname, registryList);
if (registryList!=null && !registryList.isEmpty()) { }
Collections.sort(registryList); }
StringBuilder addressListSB = new StringBuilder(); }
for (String item:registryList) {
addressListSB.append(item).append(",");
}
addressListStr = addressListSB.toString();
addressListStr = addressListStr.substring(0, addressListStr.length()-1);
}
group.setAddressList(addressListStr);
group.setUpdateTime(new Date());
XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().update(group); // fresh group address
} for (XxlJobGroup group : groupList) {
} List<String> registryList = appAddressMap.get(group.getAppname());
} catch (Exception e) { String addressListStr = null;
if (!toStop) { if (registryList != null && !registryList.isEmpty()) {
logger.error(">>>>>>>>>>> xxl-job, job registry monitor thread error:{}", e); Collections.sort(registryList);
} StringBuilder addressListSB = new StringBuilder();
} for (String item : registryList) {
try { addressListSB.append(item).append(",");
TimeUnit.SECONDS.sleep(RegistryConfig.BEAT_TIMEOUT); }
} catch (InterruptedException e) { addressListStr = addressListSB.toString();
if (!toStop) { addressListStr = addressListStr.substring(0, addressListStr.length() - 1);
logger.error(">>>>>>>>>>> xxl-job, job registry monitor thread error:{}", e); }
} group.setAddressList(addressListStr);
} group.setUpdateTime(new Date());
}
logger.info(">>>>>>>>>>> xxl-job, job registry monitor thread stop");
}
});
registryMonitorThread.setDaemon(true);
registryMonitorThread.setName("xxl-job, admin JobRegistryMonitorHelper-registryMonitorThread");
registryMonitorThread.start();
}
public void toStop(){ XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().update(group);
toStop = true; }
}
} catch (Exception e) {
if (!toStop) {
logger.error(">>>>>>>>>>> xxl-job, job registry monitor thread error:{}", e);
}
}
try {
TimeUnit.SECONDS.sleep(RegistryConfig.BEAT_TIMEOUT);
} catch (InterruptedException e) {
if (!toStop) {
logger.error(">>>>>>>>>>> xxl-job, job registry monitor thread error:{}", e);
}
}
}
logger.info(">>>>>>>>>>> xxl-job, job registry monitor thread stop");
}
});
registryMonitorThread.setDaemon(true);
registryMonitorThread.setName("xxl-job, admin JobRegistryMonitorHelper-registryMonitorThread");
registryMonitorThread.start();
}
// stop registryOrRemoveThreadPool public void toStop() {
registryOrRemoveThreadPool.shutdownNow(); toStop = true;
// stop monitir (interrupt and wait) // stop registryOrRemoveThreadPool
registryMonitorThread.interrupt(); registryOrRemoveThreadPool.shutdownNow();
try {
registryMonitorThread.join(); // stop monitir (interrupt and wait)
} catch (InterruptedException e) { registryMonitorThread.interrupt();
logger.error(e.getMessage(), e); try {
} registryMonitorThread.join();
} } catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
// ---------------------- helper ---------------------- // ---------------------- helper ----------------------
public ReturnT<String> registry(RegistryParam registryParam) { public ReturnT<String> registry(RegistryParam registryParam) {
// valid // valid
if (!StringUtils.hasText(registryParam.getRegistryGroup()) if (!StringUtils.hasText(registryParam.getRegistryGroup())
|| !StringUtils.hasText(registryParam.getRegistryKey()) || !StringUtils.hasText(registryParam.getRegistryKey())
|| !StringUtils.hasText(registryParam.getRegistryValue())) { || !StringUtils.hasText(registryParam.getRegistryValue())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument."); return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument.");
} }
// async execute // async execute
registryOrRemoveThreadPool.execute(new Runnable() { registryOrRemoveThreadPool.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryUpdate(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date()); int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryUpdate(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date());
if (ret < 1) { if (ret < 1) {
XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registrySave(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date()); XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registrySave(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date());
// fresh // fresh
freshGroupRegistryInfo(registryParam); freshGroupRegistryInfo(registryParam);
} }
} }
}); });
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
public ReturnT<String> registryRemove(RegistryParam registryParam) { public ReturnT<String> registryRemove(RegistryParam registryParam) {
// valid // valid
if (!StringUtils.hasText(registryParam.getRegistryGroup()) if (!StringUtils.hasText(registryParam.getRegistryGroup())
|| !StringUtils.hasText(registryParam.getRegistryKey()) || !StringUtils.hasText(registryParam.getRegistryKey())
|| !StringUtils.hasText(registryParam.getRegistryValue())) { || !StringUtils.hasText(registryParam.getRegistryValue())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument."); return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument.");
} }
// async execute // async execute
registryOrRemoveThreadPool.execute(new Runnable() { registryOrRemoveThreadPool.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryDelete(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue()); int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryDelete(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue());
if (ret > 0) { if (ret > 0) {
// fresh // fresh
freshGroupRegistryInfo(registryParam); freshGroupRegistryInfo(registryParam);
} }
} }
}); });
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
private void freshGroupRegistryInfo(RegistryParam registryParam){ private void freshGroupRegistryInfo(RegistryParam registryParam) {
// Under consideration, prevent affecting core tables // Under consideration, prevent affecting core tables
} }
} }

View File

@ -23,7 +23,8 @@ public class JobScheduleHelper {
private static Logger logger = LoggerFactory.getLogger(JobScheduleHelper.class); private static Logger logger = LoggerFactory.getLogger(JobScheduleHelper.class);
private static JobScheduleHelper instance = new JobScheduleHelper(); private static JobScheduleHelper instance = new JobScheduleHelper();
public static JobScheduleHelper getInstance(){
public static JobScheduleHelper getInstance() {
return instance; return instance;
} }
@ -35,7 +36,7 @@ public class JobScheduleHelper {
private volatile boolean ringThreadToStop = false; private volatile boolean ringThreadToStop = false;
private volatile static Map<Integer, List<Integer>> ringData = new ConcurrentHashMap<>(); private volatile static Map<Integer, List<Integer>> ringData = new ConcurrentHashMap<>();
public void start(){ public void start() {
// schedule thread // schedule thread
scheduleThread = new Thread(new Runnable() { scheduleThread = new Thread(new Runnable() {
@ -43,7 +44,7 @@ public class JobScheduleHelper {
public void run() { public void run() {
try { try {
TimeUnit.MILLISECONDS.sleep(5000 - System.currentTimeMillis()%1000 ); TimeUnit.MILLISECONDS.sleep(5000 - System.currentTimeMillis() % 1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
if (!scheduleThreadToStop) { if (!scheduleThreadToStop) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
@ -70,7 +71,7 @@ public class JobScheduleHelper {
connAutoCommit = conn.getAutoCommit(); connAutoCommit = conn.getAutoCommit();
conn.setAutoCommit(false); conn.setAutoCommit(false);
preparedStatement = conn.prepareStatement( "select * from xxl_job_lock where lock_name = 'schedule_lock' for update" ); preparedStatement = conn.prepareStatement("select * from xxl_job_lock where lock_name = 'schedule_lock' for update");
preparedStatement.execute(); preparedStatement.execute();
// tx start // tx start
@ -78,9 +79,9 @@ public class JobScheduleHelper {
// 1、pre read // 1、pre read
long nowTime = System.currentTimeMillis(); long nowTime = System.currentTimeMillis();
List<XxlJobInfo> scheduleList = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().scheduleJobQuery(nowTime + PRE_READ_MS, preReadCount); List<XxlJobInfo> scheduleList = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().scheduleJobQuery(nowTime + PRE_READ_MS, preReadCount);
if (scheduleList!=null && scheduleList.size()>0) { if (scheduleList != null && scheduleList.size() > 0) {
// 2、push time-ring // 2、push time-ring
for (XxlJobInfo jobInfo: scheduleList) { for (XxlJobInfo jobInfo : scheduleList) {
// time-ring jump // time-ring jump
if (nowTime > jobInfo.getTriggerNextTime() + PRE_READ_MS) { if (nowTime > jobInfo.getTriggerNextTime() + PRE_READ_MS) {
@ -92,7 +93,7 @@ public class JobScheduleHelper {
if (MisfireStrategyEnum.FIRE_ONCE_NOW == misfireStrategyEnum) { if (MisfireStrategyEnum.FIRE_ONCE_NOW == misfireStrategyEnum) {
// FIRE_ONCE_NOW 》 trigger // FIRE_ONCE_NOW 》 trigger
JobTriggerPoolHelper.trigger(jobInfo.getId(), TriggerTypeEnum.MISFIRE, -1, null, null, null); JobTriggerPoolHelper.trigger(jobInfo.getId(), TriggerTypeEnum.MISFIRE, -1, null, null, null);
logger.debug(">>>>>>>>>>> xxl-job, schedule push trigger : jobId = " + jobInfo.getId() ); logger.debug(">>>>>>>>>>> xxl-job, schedule push trigger : jobId = " + jobInfo.getId());
} }
// 2、fresh next // 2、fresh next
@ -103,16 +104,16 @@ public class JobScheduleHelper {
// 1、trigger // 1、trigger
JobTriggerPoolHelper.trigger(jobInfo.getId(), TriggerTypeEnum.CRON, -1, null, null, null); JobTriggerPoolHelper.trigger(jobInfo.getId(), TriggerTypeEnum.CRON, -1, null, null, null);
logger.debug(">>>>>>>>>>> xxl-job, schedule push trigger : jobId = " + jobInfo.getId() ); logger.debug(">>>>>>>>>>> xxl-job, schedule push trigger : jobId = " + jobInfo.getId());
// 2、fresh next // 2、fresh next
refreshNextValidTime(jobInfo, new Date()); refreshNextValidTime(jobInfo, new Date());
// next-trigger-time in 5s, pre-read again // next-trigger-time in 5s, pre-read again
if (jobInfo.getTriggerStatus()==1 && nowTime + PRE_READ_MS > jobInfo.getTriggerNextTime()) { if (jobInfo.getTriggerStatus() == 1 && nowTime + PRE_READ_MS > jobInfo.getTriggerNextTime()) {
// 1、make ring second // 1、make ring second
int ringSecond = (int)((jobInfo.getTriggerNextTime()/1000)%60); int ringSecond = (int) ((jobInfo.getTriggerNextTime() / 1000) % 60);
// 2、push time ring // 2、push time ring
pushTimeRing(ringSecond, jobInfo.getId()); pushTimeRing(ringSecond, jobInfo.getId());
@ -126,7 +127,7 @@ public class JobScheduleHelper {
// 2.3、trigger-pre-readtime-ring trigger && make next-trigger-time // 2.3、trigger-pre-readtime-ring trigger && make next-trigger-time
// 1、make ring second // 1、make ring second
int ringSecond = (int)((jobInfo.getTriggerNextTime()/1000)%60); int ringSecond = (int) ((jobInfo.getTriggerNextTime() / 1000) % 60);
// 2、push time ring // 2、push time ring
pushTimeRing(ringSecond, jobInfo.getId()); pushTimeRing(ringSecond, jobInfo.getId());
@ -139,7 +140,7 @@ public class JobScheduleHelper {
} }
// 3、update trigger info // 3、update trigger info
for (XxlJobInfo jobInfo: scheduleList) { for (XxlJobInfo jobInfo : scheduleList) {
XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().scheduleUpdate(jobInfo); XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().scheduleUpdate(jobInfo);
} }
@ -192,14 +193,14 @@ public class JobScheduleHelper {
} }
} }
} }
long cost = System.currentTimeMillis()-start; long cost = System.currentTimeMillis() - start;
// Wait seconds, align second // Wait seconds, align second
if (cost < 1000) { // scan-overtime, not wait if (cost < 1000) { // scan-overtime, not wait
try { try {
// pre-read period: success > scan each second; fail > skip this period; // pre-read period: success > scan each second; fail > skip this period;
TimeUnit.MILLISECONDS.sleep((preReadSuc?1000:PRE_READ_MS) - System.currentTimeMillis()%1000); TimeUnit.MILLISECONDS.sleep((preReadSuc ? 1000 : PRE_READ_MS) - System.currentTimeMillis() % 1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
if (!scheduleThreadToStop) { if (!scheduleThreadToStop) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
@ -238,17 +239,17 @@ public class JobScheduleHelper {
List<Integer> ringItemData = new ArrayList<>(); List<Integer> ringItemData = new ArrayList<>();
int nowSecond = Calendar.getInstance().get(Calendar.SECOND); // 避免处理耗时太长,跨过刻度,向前校验一个刻度; int nowSecond = Calendar.getInstance().get(Calendar.SECOND); // 避免处理耗时太长,跨过刻度,向前校验一个刻度;
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
List<Integer> tmpData = ringData.remove( (nowSecond+60-i)%60 ); List<Integer> tmpData = ringData.remove((nowSecond + 60 - i) % 60);
if (tmpData != null) { if (tmpData != null) {
ringItemData.addAll(tmpData); ringItemData.addAll(tmpData);
} }
} }
// ring trigger // ring trigger
logger.debug(">>>>>>>>>>> xxl-job, time-ring beat : " + nowSecond + " = " + Arrays.asList(ringItemData) ); logger.debug(">>>>>>>>>>> xxl-job, time-ring beat : " + nowSecond + " = " + Arrays.asList(ringItemData));
if (ringItemData.size() > 0) { if (ringItemData.size() > 0) {
// do trigger // do trigger
for (int jobId: ringItemData) { for (int jobId : ringItemData) {
// do trigger // do trigger
JobTriggerPoolHelper.trigger(jobId, TriggerTypeEnum.CRON, -1, null, null, null); JobTriggerPoolHelper.trigger(jobId, TriggerTypeEnum.CRON, -1, null, null, null);
} }
@ -279,11 +280,11 @@ public class JobScheduleHelper {
jobInfo.setTriggerLastTime(0); jobInfo.setTriggerLastTime(0);
jobInfo.setTriggerNextTime(0); jobInfo.setTriggerNextTime(0);
logger.warn(">>>>>>>>>>> xxl-job, refreshNextValidTime fail for job: jobId={}, scheduleType={}, scheduleConf={}", logger.warn(">>>>>>>>>>> xxl-job, refreshNextValidTime fail for job: jobId={}, scheduleType={}, scheduleConf={}",
jobInfo.getId(), jobInfo.getScheduleType(), jobInfo.getScheduleConf()); jobInfo.getId(), jobInfo.getScheduleType(), jobInfo.getScheduleConf());
} }
} }
private void pushTimeRing(int ringSecond, int jobId){ private void pushTimeRing(int ringSecond, int jobId) {
// push async ring // push async ring
List<Integer> ringItemData = ringData.get(ringSecond); List<Integer> ringItemData = ringData.get(ringSecond);
if (ringItemData == null) { if (ringItemData == null) {
@ -292,10 +293,10 @@ public class JobScheduleHelper {
} }
ringItemData.add(jobId); ringItemData.add(jobId);
logger.debug(">>>>>>>>>>> xxl-job, schedule push time-ring : " + ringSecond + " = " + Arrays.asList(ringItemData) ); logger.debug(">>>>>>>>>>> xxl-job, schedule push time-ring : " + ringSecond + " = " + Arrays.asList(ringItemData));
} }
public void toStop(){ public void toStop() {
// 1、stop schedule // 1、stop schedule
scheduleThreadToStop = true; scheduleThreadToStop = true;
@ -304,7 +305,7 @@ public class JobScheduleHelper {
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
if (scheduleThread.getState() != Thread.State.TERMINATED){ if (scheduleThread.getState() != Thread.State.TERMINATED) {
// interrupt and wait // interrupt and wait
scheduleThread.interrupt(); scheduleThread.interrupt();
try { try {
@ -319,7 +320,7 @@ public class JobScheduleHelper {
if (!ringData.isEmpty()) { if (!ringData.isEmpty()) {
for (int second : ringData.keySet()) { for (int second : ringData.keySet()) {
List<Integer> tmpData = ringData.get(second); List<Integer> tmpData = ringData.get(second);
if (tmpData!=null && tmpData.size()>0) { if (tmpData != null && tmpData.size() > 0) {
hasRingData = true; hasRingData = true;
break; break;
} }
@ -340,7 +341,7 @@ public class JobScheduleHelper {
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
if (ringThread.getState() != Thread.State.TERMINATED){ if (ringThread.getState() != Thread.State.TERMINATED) {
// interrupt and wait // interrupt and wait
ringThread.interrupt(); ringThread.interrupt();
try { try {
@ -361,7 +362,7 @@ public class JobScheduleHelper {
Date nextValidTime = new CronExpression(jobInfo.getScheduleConf()).getNextValidTimeAfter(fromTime); Date nextValidTime = new CronExpression(jobInfo.getScheduleConf()).getNextValidTimeAfter(fromTime);
return nextValidTime; return nextValidTime;
} else if (ScheduleTypeEnum.FIX_RATE == scheduleTypeEnum /*|| ScheduleTypeEnum.FIX_DELAY == scheduleTypeEnum*/) { } else if (ScheduleTypeEnum.FIX_RATE == scheduleTypeEnum /*|| ScheduleTypeEnum.FIX_DELAY == scheduleTypeEnum*/) {
return new Date(fromTime.getTime() + Integer.valueOf(jobInfo.getScheduleConf())*1000 ); return new Date(fromTime.getTime() + Integer.valueOf(jobInfo.getScheduleConf()) * 1000);
} }
return null; return null;
} }

View File

@ -24,32 +24,32 @@ public class JobTriggerPoolHelper {
private ThreadPoolExecutor fastTriggerPool = null; private ThreadPoolExecutor fastTriggerPool = null;
private ThreadPoolExecutor slowTriggerPool = null; private ThreadPoolExecutor slowTriggerPool = null;
public void start(){ public void start() {
fastTriggerPool = new ThreadPoolExecutor( fastTriggerPool = new ThreadPoolExecutor(
10, 10,
XxlJobAdminConfig.getAdminConfig().getTriggerPoolFastMax(), XxlJobAdminConfig.getAdminConfig().getTriggerPoolFastMax(),
60L, 60L,
TimeUnit.SECONDS, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(1000), new LinkedBlockingQueue<Runnable>(1000),
new ThreadFactory() { new ThreadFactory() {
@Override @Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable r) {
return new Thread(r, "xxl-job, admin JobTriggerPoolHelper-fastTriggerPool-" + r.hashCode()); return new Thread(r, "xxl-job, admin JobTriggerPoolHelper-fastTriggerPool-" + r.hashCode());
} }
}); });
slowTriggerPool = new ThreadPoolExecutor( slowTriggerPool = new ThreadPoolExecutor(
10, 10,
XxlJobAdminConfig.getAdminConfig().getTriggerPoolSlowMax(), XxlJobAdminConfig.getAdminConfig().getTriggerPoolSlowMax(),
60L, 60L,
TimeUnit.SECONDS, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(2000), new LinkedBlockingQueue<Runnable>(2000),
new ThreadFactory() { new ThreadFactory() {
@Override @Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable r) {
return new Thread(r, "xxl-job, admin JobTriggerPoolHelper-slowTriggerPool-" + r.hashCode()); return new Thread(r, "xxl-job, admin JobTriggerPoolHelper-slowTriggerPool-" + r.hashCode());
} }
}); });
} }
@ -62,7 +62,7 @@ public class JobTriggerPoolHelper {
// job timeout count // job timeout count
private volatile long minTim = System.currentTimeMillis()/60000; // ms > min private volatile long minTim = System.currentTimeMillis() / 60000; // ms > min
private volatile ConcurrentMap<Integer, AtomicInteger> jobTimeoutCountMap = new ConcurrentHashMap<>(); private volatile ConcurrentMap<Integer, AtomicInteger> jobTimeoutCountMap = new ConcurrentHashMap<>();
@ -79,7 +79,7 @@ public class JobTriggerPoolHelper {
// choose thread pool // choose thread pool
ThreadPoolExecutor triggerPool_ = fastTriggerPool; ThreadPoolExecutor triggerPool_ = fastTriggerPool;
AtomicInteger jobTimeoutCount = jobTimeoutCountMap.get(jobId); AtomicInteger jobTimeoutCount = jobTimeoutCountMap.get(jobId);
if (jobTimeoutCount!=null && jobTimeoutCount.get() > 10) { // job-timeout 10 times in 1 min if (jobTimeoutCount != null && jobTimeoutCount.get() > 10) { // job-timeout 10 times in 1 min
triggerPool_ = slowTriggerPool; triggerPool_ = slowTriggerPool;
} }
@ -98,14 +98,14 @@ public class JobTriggerPoolHelper {
} finally { } finally {
// check timeout-count-map // check timeout-count-map
long minTim_now = System.currentTimeMillis()/60000; long minTim_now = System.currentTimeMillis() / 60000;
if (minTim != minTim_now) { if (minTim != minTim_now) {
minTim = minTim_now; minTim = minTim_now;
jobTimeoutCountMap.clear(); jobTimeoutCountMap.clear();
} }
// incr timeout-count-map // incr timeout-count-map
long cost = System.currentTimeMillis()-start; long cost = System.currentTimeMillis() - start;
if (cost > 500) { // ob-timeout threshold 500ms if (cost > 500) { // ob-timeout threshold 500ms
AtomicInteger timeoutCount = jobTimeoutCountMap.putIfAbsent(jobId, new AtomicInteger(1)); AtomicInteger timeoutCount = jobTimeoutCountMap.putIfAbsent(jobId, new AtomicInteger(1));
if (timeoutCount != null) { if (timeoutCount != null) {
@ -120,7 +120,6 @@ public class JobTriggerPoolHelper {
} }
// ---------------------- helper ---------------------- // ---------------------- helper ----------------------
private static JobTriggerPoolHelper helper = new JobTriggerPoolHelper(); private static JobTriggerPoolHelper helper = new JobTriggerPoolHelper();
@ -128,6 +127,7 @@ public class JobTriggerPoolHelper {
public static void toStart() { public static void toStart() {
helper.start(); helper.start();
} }
public static void toStop() { public static void toStop() {
helper.stop(); helper.stop();
} }
@ -135,13 +135,11 @@ public class JobTriggerPoolHelper {
/** /**
* @param jobId * @param jobId
* @param triggerType * @param triggerType
* @param failRetryCount * @param failRetryCount >=0: use this param
* >=0: use this param * <0: use param from job info config
* <0: use param from job info config
* @param executorShardingParam * @param executorShardingParam
* @param executorParam * @param executorParam null: use job param
* null: use job param * not null: cover job param
* not null: cover job param
*/ */
public static void trigger(int jobId, TriggerTypeEnum triggerType, int failRetryCount, String executorShardingParam, String executorParam, String addressList) { public static void trigger(int jobId, TriggerTypeEnum triggerType, int failRetryCount, String executorShardingParam, String executorParam, String addressList) {
helper.addTrigger(jobId, triggerType, failRetryCount, executorShardingParam, executorParam, addressList); helper.addTrigger(jobId, triggerType, failRetryCount, executorShardingParam, executorParam, addressList);

View File

@ -16,10 +16,12 @@ public enum TriggerTypeEnum {
API(I18nUtil.getString("jobconf_trigger_type_api")), API(I18nUtil.getString("jobconf_trigger_type_api")),
MISFIRE(I18nUtil.getString("jobconf_trigger_type_misfire")); MISFIRE(I18nUtil.getString("jobconf_trigger_type_misfire"));
private TriggerTypeEnum(String title){ private TriggerTypeEnum(String title) {
this.title = title; this.title = title;
} }
private String title; private String title;
public String getTitle() { public String getTitle() {
return title; return title;
} }

View File

@ -30,16 +30,13 @@ public class XxlJobTrigger {
* *
* @param jobId * @param jobId
* @param triggerType * @param triggerType
* @param failRetryCount * @param failRetryCount >=0: use this param
* >=0: use this param * <0: use param from job info config
* <0: use param from job info config
* @param executorShardingParam * @param executorShardingParam
* @param executorParam * @param executorParam null: use job param
* null: use job param * not null: cover job param
* not null: cover job param * @param addressList null: use executor addressList
* @param addressList * not null: cover
* null: use executor addressList
* not null: cover
*/ */
public static void trigger(int jobId, public static void trigger(int jobId,
TriggerTypeEnum triggerType, TriggerTypeEnum triggerType,
@ -57,28 +54,28 @@ public class XxlJobTrigger {
if (executorParam != null) { if (executorParam != null) {
jobInfo.setExecutorParam(executorParam); jobInfo.setExecutorParam(executorParam);
} }
int finalFailRetryCount = failRetryCount>=0?failRetryCount:jobInfo.getExecutorFailRetryCount(); int finalFailRetryCount = failRetryCount >= 0 ? failRetryCount : jobInfo.getExecutorFailRetryCount();
XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(jobInfo.getJobGroup()); XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(jobInfo.getJobGroup());
// cover addressList // cover addressList
if (addressList!=null && addressList.trim().length()>0) { if (addressList != null && addressList.trim().length() > 0) {
group.setAddressType(1); group.setAddressType(1);
group.setAddressList(addressList.trim()); group.setAddressList(addressList.trim());
} }
// sharding param // sharding param
int[] shardingParam = null; int[] shardingParam = null;
if (executorShardingParam!=null){ if (executorShardingParam != null) {
String[] shardingArr = executorShardingParam.split("/"); String[] shardingArr = executorShardingParam.split("/");
if (shardingArr.length==2 && isNumeric(shardingArr[0]) && isNumeric(shardingArr[1])) { if (shardingArr.length == 2 && isNumeric(shardingArr[0]) && isNumeric(shardingArr[1])) {
shardingParam = new int[2]; shardingParam = new int[2];
shardingParam[0] = Integer.valueOf(shardingArr[0]); shardingParam[0] = Integer.valueOf(shardingArr[0]);
shardingParam[1] = Integer.valueOf(shardingArr[1]); shardingParam[1] = Integer.valueOf(shardingArr[1]);
} }
} }
if (ExecutorRouteStrategyEnum.SHARDING_BROADCAST==ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) if (ExecutorRouteStrategyEnum.SHARDING_BROADCAST == ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null)
&& group.getRegistryList()!=null && !group.getRegistryList().isEmpty() && group.getRegistryList() != null && !group.getRegistryList().isEmpty()
&& shardingParam==null) { && shardingParam == null) {
for (int i = 0; i < group.getRegistryList().size(); i++) { for (int i = 0; i < group.getRegistryList().size(); i++) {
processTrigger(group, jobInfo, finalFailRetryCount, triggerType, i, group.getRegistryList().size()); processTrigger(group, jobInfo, finalFailRetryCount, triggerType, i, group.getRegistryList().size());
} }
@ -91,7 +88,7 @@ public class XxlJobTrigger {
} }
private static boolean isNumeric(String str){ private static boolean isNumeric(String str) {
try { try {
int result = Integer.valueOf(str); int result = Integer.valueOf(str);
return true; return true;
@ -101,19 +98,19 @@ public class XxlJobTrigger {
} }
/** /**
* @param group job group, registry list may be empty * @param group job group, registry list may be empty
* @param jobInfo * @param jobInfo
* @param finalFailRetryCount * @param finalFailRetryCount
* @param triggerType * @param triggerType
* @param index sharding index * @param index sharding index
* @param total sharding index * @param total sharding index
*/ */
private static void processTrigger(XxlJobGroup group, XxlJobInfo jobInfo, int finalFailRetryCount, TriggerTypeEnum triggerType, int index, int total){ private static void processTrigger(XxlJobGroup group, XxlJobInfo jobInfo, int finalFailRetryCount, TriggerTypeEnum triggerType, int index, int total) {
// param // param
ExecutorBlockStrategyEnum blockStrategy = ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), ExecutorBlockStrategyEnum.SERIAL_EXECUTION); // block strategy ExecutorBlockStrategyEnum blockStrategy = ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), ExecutorBlockStrategyEnum.SERIAL_EXECUTION); // block strategy
ExecutorRouteStrategyEnum executorRouteStrategyEnum = ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null); // route strategy ExecutorRouteStrategyEnum executorRouteStrategyEnum = ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null); // route strategy
String shardingParam = (ExecutorRouteStrategyEnum.SHARDING_BROADCAST==executorRouteStrategyEnum)?String.valueOf(index).concat("/").concat(String.valueOf(total)):null; String shardingParam = (ExecutorRouteStrategyEnum.SHARDING_BROADCAST == executorRouteStrategyEnum) ? String.valueOf(index).concat("/").concat(String.valueOf(total)) : null;
// 1、save log-id // 1、save log-id
XxlJobLog jobLog = new XxlJobLog(); XxlJobLog jobLog = new XxlJobLog();
@ -141,7 +138,7 @@ public class XxlJobTrigger {
// 3、init address // 3、init address
String address = null; String address = null;
ReturnT<String> routeAddressResult = null; ReturnT<String> routeAddressResult = null;
if (group.getRegistryList()!=null && !group.getRegistryList().isEmpty()) { if (group.getRegistryList() != null && !group.getRegistryList().isEmpty()) {
if (ExecutorRouteStrategyEnum.SHARDING_BROADCAST == executorRouteStrategyEnum) { if (ExecutorRouteStrategyEnum.SHARDING_BROADCAST == executorRouteStrategyEnum) {
if (index < group.getRegistryList().size()) { if (index < group.getRegistryList().size()) {
address = group.getRegistryList().get(index); address = group.getRegistryList().get(index);
@ -171,18 +168,18 @@ public class XxlJobTrigger {
triggerMsgSb.append(I18nUtil.getString("jobconf_trigger_type")).append("").append(triggerType.getTitle()); triggerMsgSb.append(I18nUtil.getString("jobconf_trigger_type")).append("").append(triggerType.getTitle());
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_admin_adress")).append("").append(IpUtil.getIp()); triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_admin_adress")).append("").append(IpUtil.getIp());
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_exe_regtype")).append("") triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_exe_regtype")).append("")
.append( (group.getAddressType() == 0)?I18nUtil.getString("jobgroup_field_addressType_0"):I18nUtil.getString("jobgroup_field_addressType_1") ); .append((group.getAddressType() == 0) ? I18nUtil.getString("jobgroup_field_addressType_0") : I18nUtil.getString("jobgroup_field_addressType_1"));
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_exe_regaddress")).append("").append(group.getRegistryList()); triggerMsgSb.append("<br>").append(I18nUtil.getString("jobconf_trigger_exe_regaddress")).append("").append(group.getRegistryList());
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_executorRouteStrategy")).append("").append(executorRouteStrategyEnum.getTitle()); triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_executorRouteStrategy")).append("").append(executorRouteStrategyEnum.getTitle());
if (shardingParam != null) { if (shardingParam != null) {
triggerMsgSb.append("("+shardingParam+")"); triggerMsgSb.append("(" + shardingParam + ")");
} }
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_executorBlockStrategy")).append("").append(blockStrategy.getTitle()); triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_executorBlockStrategy")).append("").append(blockStrategy.getTitle());
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_timeout")).append("").append(jobInfo.getExecutorTimeout()); triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_timeout")).append("").append(jobInfo.getExecutorTimeout());
triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_executorFailRetryCount")).append("").append(finalFailRetryCount); triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_executorFailRetryCount")).append("").append(finalFailRetryCount);
triggerMsgSb.append("<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_run") +"<<<<<<<<<<< </span><br>") triggerMsgSb.append("<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>" + I18nUtil.getString("jobconf_trigger_run") + "<<<<<<<<<<< </span><br>")
.append((routeAddressResult!=null&&routeAddressResult.getMsg()!=null)?routeAddressResult.getMsg()+"<br><br>":"").append(triggerResult.getMsg()!=null?triggerResult.getMsg():""); .append((routeAddressResult != null && routeAddressResult.getMsg() != null) ? routeAddressResult.getMsg() + "<br><br>" : "").append(triggerResult.getMsg() != null ? triggerResult.getMsg() : "");
// 6、save log trigger-info // 6、save log trigger-info
jobLog.setExecutorAddress(address); jobLog.setExecutorAddress(address);
@ -200,11 +197,12 @@ public class XxlJobTrigger {
/** /**
* run executor * run executor
*
* @param triggerParam * @param triggerParam
* @param address * @param address
* @return * @return
*/ */
public static ReturnT<String> runExecutor(TriggerParam triggerParam, String address){ public static ReturnT<String> runExecutor(TriggerParam triggerParam, String address) {
ReturnT<String> runResult = null; ReturnT<String> runResult = null;
try { try {
ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(address); ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(address);

View File

@ -11,88 +11,88 @@ import javax.servlet.http.HttpServletResponse;
*/ */
public class CookieUtil { public class CookieUtil {
// 默认缓存时间,单位/秒, 2H // 默认缓存时间,单位/秒, 2H
private static final int COOKIE_MAX_AGE = Integer.MAX_VALUE; private static final int COOKIE_MAX_AGE = Integer.MAX_VALUE;
// 保存路径,根路径 // 保存路径,根路径
private static final String COOKIE_PATH = "/"; private static final String COOKIE_PATH = "/";
/** /**
* *
* *
* @param response * @param response
* @param key * @param key
* @param value * @param value
* @param ifRemember * @param ifRemember
*/ */
public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) { public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) {
int age = ifRemember?COOKIE_MAX_AGE:-1; int age = ifRemember ? COOKIE_MAX_AGE : -1;
set(response, key, value, null, COOKIE_PATH, age, true); set(response, key, value, null, COOKIE_PATH, age, true);
} }
/** /**
* *
* *
* @param response * @param response
* @param key * @param key
* @param value * @param value
* @param maxAge * @param maxAge
*/ */
private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) { private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) {
Cookie cookie = new Cookie(key, value); Cookie cookie = new Cookie(key, value);
if (domain != null) { if (domain != null) {
cookie.setDomain(domain); cookie.setDomain(domain);
} }
cookie.setPath(path); cookie.setPath(path);
cookie.setMaxAge(maxAge); cookie.setMaxAge(maxAge);
cookie.setHttpOnly(isHttpOnly); cookie.setHttpOnly(isHttpOnly);
response.addCookie(cookie); response.addCookie(cookie);
} }
/** /**
* value * value
* *
* @param request * @param request
* @param key * @param key
* @return * @return
*/ */
public static String getValue(HttpServletRequest request, String key) { public static String getValue(HttpServletRequest request, String key) {
Cookie cookie = get(request, key); Cookie cookie = get(request, key);
if (cookie != null) { if (cookie != null) {
return cookie.getValue(); return cookie.getValue();
} }
return null; return null;
} }
/** /**
* Cookie * Cookie
* *
* @param request * @param request
* @param key * @param key
*/ */
private static Cookie get(HttpServletRequest request, String key) { private static Cookie get(HttpServletRequest request, String key) {
Cookie[] arr_cookie = request.getCookies(); Cookie[] arr_cookie = request.getCookies();
if (arr_cookie != null && arr_cookie.length > 0) { if (arr_cookie != null && arr_cookie.length > 0) {
for (Cookie cookie : arr_cookie) { for (Cookie cookie : arr_cookie) {
if (cookie.getName().equals(key)) { if (cookie.getName().equals(key)) {
return cookie; return cookie;
} }
} }
} }
return null; return null;
} }
/** /**
* Cookie * Cookie
* *
* @param request * @param request
* @param response * @param response
* @param key * @param key
*/ */
public static void remove(HttpServletRequest request, HttpServletResponse response, String key) { public static void remove(HttpServletRequest request, HttpServletResponse response, String key) {
Cookie cookie = get(request, key); Cookie cookie = get(request, key);
if (cookie != null) { if (cookie != null) {
set(response, key, "", null, COOKIE_PATH, 0, true); set(response, key, "", null, COOKIE_PATH, 0, true);
} }
} }
} }

View File

@ -23,7 +23,8 @@ public class I18nUtil {
private static Logger logger = LoggerFactory.getLogger(I18nUtil.class); private static Logger logger = LoggerFactory.getLogger(I18nUtil.class);
private static Properties prop = null; private static Properties prop = null;
public static Properties loadI18nProp(){
public static Properties loadI18nProp() {
if (prop != null) { if (prop != null) {
return prop; return prop;
} }
@ -34,7 +35,7 @@ public class I18nUtil {
// load prop // load prop
Resource resource = new ClassPathResource(i18nFile); Resource resource = new ClassPathResource(i18nFile);
EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
prop = PropertiesLoaderUtils.loadProperties(encodedResource); prop = PropertiesLoaderUtils.loadProperties(encodedResource);
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
@ -62,12 +63,12 @@ public class I18nUtil {
Map<String, String> map = new HashMap<String, String>(); Map<String, String> map = new HashMap<String, String>();
Properties prop = loadI18nProp(); Properties prop = loadI18nProp();
if (keys!=null && keys.length>0) { if (keys != null && keys.length > 0) {
for (String key: keys) { for (String key : keys) {
map.put(key, prop.getProperty(key)); map.put(key, prop.getProperty(key));
} }
} else { } else {
for (String key: prop.stringPropertyNames()) { for (String key : prop.stringPropertyNames()) {
map.put(key, prop.getProperty(key)); map.put(key, prop.getProperty(key));
} }
} }

View File

@ -12,16 +12,17 @@ import java.io.IOException;
/** /**
* Jackson util * Jackson util
* * <p>
* 1obj need private and set/get * 1obj need private and set/get
* 2do not support inner class * 2do not support inner class
* *
* @author xuxueli 2015-9-25 18:02:56 * @author xuxueli 2015-9-25 18:02:56
*/ */
public class JacksonUtil { public class JacksonUtil {
private static Logger logger = LoggerFactory.getLogger(JacksonUtil.class); private static Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
private final static ObjectMapper objectMapper = new ObjectMapper(); private final static ObjectMapper objectMapper = new ObjectMapper();
public static ObjectMapper getInstance() { public static ObjectMapper getInstance() {
return objectMapper; return objectMapper;
} }
@ -34,15 +35,15 @@ public class JacksonUtil {
* @throws Exception * @throws Exception
*/ */
public static String writeValueAsString(Object obj) { public static String writeValueAsString(Object obj) {
try { try {
return getInstance().writeValueAsString(obj); return getInstance().writeValueAsString(obj);
} catch (JsonGenerationException e) { } catch (JsonGenerationException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} catch (JsonMappingException e) { } catch (JsonMappingException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
return null; return null;
} }
@ -55,38 +56,38 @@ public class JacksonUtil {
* @throws Exception * @throws Exception
*/ */
public static <T> T readValue(String jsonStr, Class<T> clazz) { public static <T> T readValue(String jsonStr, Class<T> clazz) {
try { try {
return getInstance().readValue(jsonStr, clazz); return getInstance().readValue(jsonStr, clazz);
} catch (JsonParseException e) { } catch (JsonParseException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} catch (JsonMappingException e) { } catch (JsonMappingException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
return null; return null;
} }
/** /**
* string --> List<Bean>... * string --> List<Bean>...
* *
* @param jsonStr * @param jsonStr
* @param parametrized * @param parametrized
* @param parameterClasses * @param parameterClasses
* @param <T> * @param <T>
* @return * @return
*/ */
public static <T> T readValue(String jsonStr, Class<?> parametrized, Class<?>... parameterClasses) { public static <T> T readValue(String jsonStr, Class<?> parametrized, Class<?>... parameterClasses) {
try { try {
JavaType javaType = getInstance().getTypeFactory().constructParametricType(parametrized, parameterClasses); JavaType javaType = getInstance().getTypeFactory().constructParametricType(parametrized, parameterClasses);
return getInstance().readValue(jsonStr, javaType); return getInstance().readValue(jsonStr, javaType);
} catch (JsonParseException e) { } catch (JsonParseException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} catch (JsonMappingException e) { } catch (JsonMappingException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
return null; return null;
} }
} }

View File

@ -11,7 +11,8 @@ import java.util.concurrent.ConcurrentMap;
public class LocalCacheUtil { public class LocalCacheUtil {
private static ConcurrentMap<String, LocalCacheData> cacheRepository = new ConcurrentHashMap<String, LocalCacheData>(); // 类型建议用抽象父类,兼容性更好; private static ConcurrentMap<String, LocalCacheData> cacheRepository = new ConcurrentHashMap<String, LocalCacheData>(); // 类型建议用抽象父类,兼容性更好;
private static class LocalCacheData{
private static class LocalCacheData {
private String key; private String key;
private Object val; private Object val;
private long timeoutTime; private long timeoutTime;
@ -59,13 +60,13 @@ public class LocalCacheUtil {
* @param cacheTime * @param cacheTime
* @return * @return
*/ */
public static boolean set(String key, Object val, long cacheTime){ public static boolean set(String key, Object val, long cacheTime) {
// clean timeout cache, before set new cache (avoid cache too much) // clean timeout cache, before set new cache (avoid cache too much)
cleanTimeoutCache(); cleanTimeoutCache();
// set new cache // set new cache
if (key==null || key.trim().length()==0) { if (key == null || key.trim().length() == 0) {
return false; return false;
} }
if (val == null) { if (val == null) {
@ -86,8 +87,8 @@ public class LocalCacheUtil {
* @param key * @param key
* @return * @return
*/ */
public static boolean remove(String key){ public static boolean remove(String key) {
if (key==null || key.trim().length()==0) { if (key == null || key.trim().length() == 0) {
return false; return false;
} }
cacheRepository.remove(key); cacheRepository.remove(key);
@ -100,12 +101,12 @@ public class LocalCacheUtil {
* @param key * @param key
* @return * @return
*/ */
public static Object get(String key){ public static Object get(String key) {
if (key==null || key.trim().length()==0) { if (key == null || key.trim().length() == 0) {
return null; return null;
} }
LocalCacheData localCacheData = cacheRepository.get(key); LocalCacheData localCacheData = cacheRepository.get(key);
if (localCacheData!=null && System.currentTimeMillis()<localCacheData.getTimeoutTime()) { if (localCacheData != null && System.currentTimeMillis() < localCacheData.getTimeoutTime()) {
return localCacheData.getVal(); return localCacheData.getVal();
} else { } else {
remove(key); remove(key);
@ -118,11 +119,11 @@ public class LocalCacheUtil {
* *
* @return * @return
*/ */
public static boolean cleanTimeoutCache(){ public static boolean cleanTimeoutCache() {
if (!cacheRepository.keySet().isEmpty()) { if (!cacheRepository.keySet().isEmpty()) {
for (String key: cacheRepository.keySet()) { for (String key : cacheRepository.keySet()) {
LocalCacheData localCacheData = cacheRepository.get(key); LocalCacheData localCacheData = cacheRepository.get(key);
if (localCacheData!=null && System.currentTimeMillis()>=localCacheData.getTimeoutTime()) { if (localCacheData != null && System.currentTimeMillis() >= localCacheData.getTimeoutTime()) {
cacheRepository.remove(key); cacheRepository.remove(key);
} }
} }

View File

@ -9,41 +9,43 @@ import java.util.List;
/** /**
* job info * job info
*
* @author xuxueli 2016-1-12 18:03:45 * @author xuxueli 2016-1-12 18:03:45
*/ */
@Mapper @Mapper
public interface XxlJobInfoDao { public interface XxlJobInfoDao {
public List<XxlJobInfo> pageList(@Param("offset") int offset, public List<XxlJobInfo> pageList(@Param("offset") int offset,
@Param("pagesize") int pagesize, @Param("pagesize") int pagesize,
@Param("jobGroup") int jobGroup, @Param("jobGroup") int jobGroup,
@Param("triggerStatus") int triggerStatus, @Param("triggerStatus") int triggerStatus,
@Param("jobDesc") String jobDesc, @Param("jobDesc") String jobDesc,
@Param("executorHandler") String executorHandler, @Param("executorHandler") String executorHandler,
@Param("author") String author); @Param("author") String author);
public int pageListCount(@Param("offset") int offset,
@Param("pagesize") int pagesize,
@Param("jobGroup") int jobGroup,
@Param("triggerStatus") int triggerStatus,
@Param("jobDesc") String jobDesc,
@Param("executorHandler") String executorHandler,
@Param("author") String author);
public int save(XxlJobInfo info); public int pageListCount(@Param("offset") int offset,
@Param("pagesize") int pagesize,
@Param("jobGroup") int jobGroup,
@Param("triggerStatus") int triggerStatus,
@Param("jobDesc") String jobDesc,
@Param("executorHandler") String executorHandler,
@Param("author") String author);
public XxlJobInfo loadById(@Param("id") int id); public int save(XxlJobInfo info);
public int update(XxlJobInfo xxlJobInfo); public XxlJobInfo loadById(@Param("id") int id);
public int delete(@Param("id") long id); public int update(XxlJobInfo xxlJobInfo);
public List<XxlJobInfo> getJobsByGroup(@Param("jobGroup") int jobGroup); public int delete(@Param("id") long id);
public int findAllCount(); public List<XxlJobInfo> getJobsByGroup(@Param("jobGroup") int jobGroup);
public List<XxlJobInfo> scheduleJobQuery(@Param("maxNextTime") long maxNextTime, @Param("pagesize") int pagesize ); public int findAllCount();
public int scheduleUpdate(XxlJobInfo xxlJobInfo); public List<XxlJobInfo> scheduleJobQuery(@Param("maxNextTime") long maxNextTime, @Param("pagesize") int pagesize);
public int scheduleUpdate(XxlJobInfo xxlJobInfo);
} }

View File

@ -10,53 +10,56 @@ import java.util.Map;
/** /**
* job log * job log
*
* @author xuxueli 2016-1-12 18:03:06 * @author xuxueli 2016-1-12 18:03:06
*/ */
@Mapper @Mapper
public interface XxlJobLogDao { public interface XxlJobLogDao {
// exist jobId not use jobGroup, not exist use jobGroup // exist jobId not use jobGroup, not exist use jobGroup
public List<XxlJobLog> pageList(@Param("offset") int offset, public List<XxlJobLog> pageList(@Param("offset") int offset,
@Param("pagesize") int pagesize, @Param("pagesize") int pagesize,
@Param("jobGroup") int jobGroup, @Param("jobGroup") int jobGroup,
@Param("jobId") int jobId, @Param("jobId") int jobId,
@Param("triggerTimeStart") Date triggerTimeStart, @Param("triggerTimeStart") Date triggerTimeStart,
@Param("triggerTimeEnd") Date triggerTimeEnd, @Param("triggerTimeEnd") Date triggerTimeEnd,
@Param("logStatus") int logStatus); @Param("logStatus") int logStatus);
public int pageListCount(@Param("offset") int offset,
@Param("pagesize") int pagesize,
@Param("jobGroup") int jobGroup,
@Param("jobId") int jobId,
@Param("triggerTimeStart") Date triggerTimeStart,
@Param("triggerTimeEnd") Date triggerTimeEnd,
@Param("logStatus") int logStatus);
public XxlJobLog load(@Param("id") long id); public int pageListCount(@Param("offset") int offset,
@Param("pagesize") int pagesize,
@Param("jobGroup") int jobGroup,
@Param("jobId") int jobId,
@Param("triggerTimeStart") Date triggerTimeStart,
@Param("triggerTimeEnd") Date triggerTimeEnd,
@Param("logStatus") int logStatus);
public long save(XxlJobLog xxlJobLog); public XxlJobLog load(@Param("id") long id);
public int updateTriggerInfo(XxlJobLog xxlJobLog); public long save(XxlJobLog xxlJobLog);
public int updateHandleInfo(XxlJobLog xxlJobLog); public int updateTriggerInfo(XxlJobLog xxlJobLog);
public int delete(@Param("jobId") int jobId); public int updateHandleInfo(XxlJobLog xxlJobLog);
public Map<String, Object> findLogReport(@Param("from") Date from, public int delete(@Param("jobId") int jobId);
@Param("to") Date to);
public List<Long> findClearLogIds(@Param("jobGroup") int jobGroup, public Map<String, Object> findLogReport(@Param("from") Date from,
@Param("jobId") int jobId, @Param("to") Date to);
@Param("clearBeforeTime") Date clearBeforeTime,
@Param("clearBeforeNum") int clearBeforeNum,
@Param("pagesize") int pagesize);
public int clearLog(@Param("logIds") List<Long> logIds);
public List<Long> findFailJobLogIds(@Param("pagesize") int pagesize); public List<Long> findClearLogIds(@Param("jobGroup") int jobGroup,
@Param("jobId") int jobId,
@Param("clearBeforeTime") Date clearBeforeTime,
@Param("clearBeforeNum") int clearBeforeNum,
@Param("pagesize") int pagesize);
public int updateAlarmStatus(@Param("logId") long logId, public int clearLog(@Param("logIds") List<Long> logIds);
@Param("oldAlarmStatus") int oldAlarmStatus,
@Param("newAlarmStatus") int newAlarmStatus);
public List<Long> findLostJobIds(@Param("losedTime") Date losedTime); public List<Long> findFailJobLogIds(@Param("pagesize") int pagesize);
public int updateAlarmStatus(@Param("logId") long logId,
@Param("oldAlarmStatus") int oldAlarmStatus,
@Param("newAlarmStatus") int newAlarmStatus);
public List<Long> findLostJobIds(@Param("losedTime") Date losedTime);
} }

View File

@ -8,17 +8,18 @@ import java.util.List;
/** /**
* job log for glue * job log for glue
*
* @author xuxueli 2016-5-19 18:04:56 * @author xuxueli 2016-5-19 18:04:56
*/ */
@Mapper @Mapper
public interface XxlJobLogGlueDao { public interface XxlJobLogGlueDao {
public int save(XxlJobLogGlue xxlJobLogGlue); public int save(XxlJobLogGlue xxlJobLogGlue);
public List<XxlJobLogGlue> findByJobId(@Param("jobId") int jobId); public List<XxlJobLogGlue> findByJobId(@Param("jobId") int jobId);
public int removeOld(@Param("jobId") int jobId, @Param("limit") int limit); public int removeOld(@Param("jobId") int jobId, @Param("limit") int limit);
public int deleteByJobId(@Param("jobId") int jobId); public int deleteByJobId(@Param("jobId") int jobId);
} }

View File

@ -9,18 +9,19 @@ import java.util.List;
/** /**
* job log * job log
*
* @author xuxueli 2019-11-22 * @author xuxueli 2019-11-22
*/ */
@Mapper @Mapper
public interface XxlJobLogReportDao { public interface XxlJobLogReportDao {
public int save(XxlJobLogReport xxlJobLogReport); public int save(XxlJobLogReport xxlJobLogReport);
public int update(XxlJobLogReport xxlJobLogReport); public int update(XxlJobLogReport xxlJobLogReport);
public List<XxlJobLogReport> queryLogReport(@Param("triggerDayFrom") Date triggerDayFrom, public List<XxlJobLogReport> queryLogReport(@Param("triggerDayFrom") Date triggerDayFrom,
@Param("triggerDayTo") Date triggerDayTo); @Param("triggerDayTo") Date triggerDayTo);
public XxlJobLogReport queryLogReportTotal(); public XxlJobLogReport queryLogReportTotal();
} }

View File

@ -32,7 +32,7 @@ public interface XxlJobRegistryDao {
@Param("updateTime") Date updateTime); @Param("updateTime") Date updateTime);
public int registryDelete(@Param("registryGroup") String registryGroup, public int registryDelete(@Param("registryGroup") String registryGroup,
@Param("registryKey") String registryKey, @Param("registryKey") String registryKey,
@Param("registryValue") String registryValue); @Param("registryValue") String registryValue);
} }

View File

@ -3,6 +3,7 @@ package com.xxl.job.admin.dao;
import com.xxl.job.admin.core.model.XxlJobUser; import com.xxl.job.admin.core.model.XxlJobUser;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
/** /**
@ -11,21 +12,22 @@ import java.util.List;
@Mapper @Mapper
public interface XxlJobUserDao { public interface XxlJobUserDao {
public List<XxlJobUser> pageList(@Param("offset") int offset, public List<XxlJobUser> pageList(@Param("offset") int offset,
@Param("pagesize") int pagesize, @Param("pagesize") int pagesize,
@Param("username") String username, @Param("username") String username,
@Param("role") int role); @Param("role") int role);
public int pageListCount(@Param("offset") int offset,
@Param("pagesize") int pagesize,
@Param("username") String username,
@Param("role") int role);
public XxlJobUser loadByUserName(@Param("username") String username); public int pageListCount(@Param("offset") int offset,
@Param("pagesize") int pagesize,
@Param("username") String username,
@Param("role") int role);
public int save(XxlJobUser xxlJobUser); public XxlJobUser loadByUserName(@Param("username") String username);
public int update(XxlJobUser xxlJobUser); public int save(XxlJobUser xxlJobUser);
public int delete(@Param("id") int id); public int update(XxlJobUser xxlJobUser);
public int delete(@Param("id") int id);
} }

View File

@ -26,12 +26,13 @@ public class LoginService {
private XxlJobUserDao xxlJobUserDao; private XxlJobUserDao xxlJobUserDao;
private String makeToken(XxlJobUser xxlJobUser){ private String makeToken(XxlJobUser xxlJobUser) {
String tokenJson = JacksonUtil.writeValueAsString(xxlJobUser); String tokenJson = JacksonUtil.writeValueAsString(xxlJobUser);
String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16); String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16);
return tokenHex; return tokenHex;
} }
private XxlJobUser parseToken(String tokenHex){
private XxlJobUser parseToken(String tokenHex) {
XxlJobUser xxlJobUser = null; XxlJobUser xxlJobUser = null;
if (tokenHex != null) { if (tokenHex != null) {
String tokenJson = new String(new BigInteger(tokenHex, 16).toByteArray()); // username_password(md5) String tokenJson = new String(new BigInteger(tokenHex, 16).toByteArray()); // username_password(md5)
@ -41,10 +42,10 @@ public class LoginService {
} }
public ReturnT<String> login(HttpServletRequest request, HttpServletResponse response, String username, String password, boolean ifRemember){ public ReturnT<String> login(HttpServletRequest request, HttpServletResponse response, String username, String password, boolean ifRemember) {
// param // param
if (username==null || username.trim().length()==0 || password==null || password.trim().length()==0){ if (username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0) {
return new ReturnT<String>(500, I18nUtil.getString("login_param_empty")); return new ReturnT<String>(500, I18nUtil.getString("login_param_empty"));
} }
@ -71,7 +72,7 @@ public class LoginService {
* @param request * @param request
* @param response * @param response
*/ */
public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){ public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response) {
CookieUtil.remove(request, response, LOGIN_IDENTITY_KEY); CookieUtil.remove(request, response, LOGIN_IDENTITY_KEY);
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
@ -82,7 +83,7 @@ public class LoginService {
* @param request * @param request
* @return * @return
*/ */
public XxlJobUser ifLogin(HttpServletRequest request, HttpServletResponse response){ public XxlJobUser ifLogin(HttpServletRequest request, HttpServletResponse response) {
String cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY_KEY); String cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY_KEY);
if (cookieToken != null) { if (cookieToken != null) {
XxlJobUser cookieUser = null; XxlJobUser cookieUser = null;
@ -103,8 +104,5 @@ public class LoginService {
return null; return null;
} }
public static void main(String[] args) {
System.out.println("121312");
}
} }

View File

@ -14,73 +14,74 @@ import java.util.Map;
*/ */
public interface XxlJobService { public interface XxlJobService {
/** /**
* page list * page list
* *
* @param start * @param start
* @param length * @param length
* @param jobGroup * @param jobGroup
* @param jobDesc * @param jobDesc
* @param executorHandler * @param executorHandler
* @param author * @param author
* @return * @return
*/ */
public Map<String, Object> pageList(int start, int length, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author); public Map<String, Object> pageList(int start, int length, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author);
/** /**
* add job * add job
* *
* @param jobInfo * @param jobInfo
* @return * @return
*/ */
public ReturnT<String> add(XxlJobInfo jobInfo); public ReturnT<String> add(XxlJobInfo jobInfo);
/** /**
* update job * update job
* *
* @param jobInfo * @param jobInfo
* @return * @return
*/ */
public ReturnT<String> update(XxlJobInfo jobInfo); public ReturnT<String> update(XxlJobInfo jobInfo);
/** /**
* remove job * remove job
* * * *
* @param id *
* @return * @param id
*/ * @return
public ReturnT<String> remove(int id); */
public ReturnT<String> remove(int id);
/** /**
* start job * start job
* *
* @param id * @param id
* @return * @return
*/ */
public ReturnT<String> start(int id); public ReturnT<String> start(int id);
/** /**
* stop job * stop job
* *
* @param id * @param id
* @return * @return
*/ */
public ReturnT<String> stop(int id); public ReturnT<String> stop(int id);
/** /**
* dashboard info * dashboard info
* *
* @return * @return
*/ */
public Map<String,Object> dashboardInfo(); public Map<String, Object> dashboardInfo();
/** /**
* chart info * chart info
* *
* @param startDate * @param startDate
* @param endDate * @param endDate
* @return * @return
*/ */
public ReturnT<Map<String,Object>> chartInfo(Date startDate, Date endDate); public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate);
} }

View File

@ -25,410 +25,411 @@ import java.util.*;
/** /**
* core job action for xxl-job * core job action for xxl-job
*
* @author xuxueli 2016-5-28 15:30:33 * @author xuxueli 2016-5-28 15:30:33
*/ */
@Service @Service
public class XxlJobServiceImpl implements XxlJobService { public class XxlJobServiceImpl implements XxlJobService {
private static Logger logger = LoggerFactory.getLogger(XxlJobServiceImpl.class); private static Logger logger = LoggerFactory.getLogger(XxlJobServiceImpl.class);
@Resource @Resource
private XxlJobGroupDao xxlJobGroupDao; private XxlJobGroupDao xxlJobGroupDao;
@Resource @Resource
private XxlJobInfoDao xxlJobInfoDao; private XxlJobInfoDao xxlJobInfoDao;
@Resource @Resource
public XxlJobLogDao xxlJobLogDao; public XxlJobLogDao xxlJobLogDao;
@Resource @Resource
private XxlJobLogGlueDao xxlJobLogGlueDao; private XxlJobLogGlueDao xxlJobLogGlueDao;
@Resource @Resource
private XxlJobLogReportDao xxlJobLogReportDao; private XxlJobLogReportDao xxlJobLogReportDao;
@Override @Override
public Map<String, Object> pageList(int start, int length, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) { public Map<String, Object> pageList(int start, int length, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) {
// page list // page list
List<XxlJobInfo> list = xxlJobInfoDao.pageList(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author); List<XxlJobInfo> list = xxlJobInfoDao.pageList(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author);
int list_count = xxlJobInfoDao.pageListCount(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author); int list_count = xxlJobInfoDao.pageListCount(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author);
// package result // package result
Map<String, Object> maps = new HashMap<String, Object>(); Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数 maps.put("recordsTotal", list_count); // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数 maps.put("recordsFiltered", list_count); // 过滤后的总记录数
maps.put("data", list); // 分页列表 maps.put("data", list); // 分页列表
return maps; return maps;
} }
@Override @Override
public ReturnT<String> add(XxlJobInfo jobInfo) { public ReturnT<String> add(XxlJobInfo jobInfo) {
// valid base // valid base
XxlJobGroup group = xxlJobGroupDao.load(jobInfo.getJobGroup()); XxlJobGroup group = xxlJobGroupDao.load(jobInfo.getJobGroup());
if (group == null) { if (group == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_choose")+I18nUtil.getString("jobinfo_field_jobgroup")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_choose") + I18nUtil.getString("jobinfo_field_jobgroup")));
} }
if (jobInfo.getJobDesc()==null || jobInfo.getJobDesc().trim().length()==0) { if (jobInfo.getJobDesc() == null || jobInfo.getJobDesc().trim().length() == 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_jobdesc")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_jobdesc")));
} }
if (jobInfo.getAuthor()==null || jobInfo.getAuthor().trim().length()==0) { if (jobInfo.getAuthor() == null || jobInfo.getAuthor().trim().length() == 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_author")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_author")));
} }
// valid trigger // valid trigger
ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(jobInfo.getScheduleType(), null); ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(jobInfo.getScheduleType(), null);
if (scheduleTypeEnum == null) { if (scheduleTypeEnum == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
if (scheduleTypeEnum == ScheduleTypeEnum.CRON) { if (scheduleTypeEnum == ScheduleTypeEnum.CRON) {
if (jobInfo.getScheduleConf()==null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) { if (jobInfo.getScheduleConf() == null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron"+I18nUtil.getString("system_unvalid")); return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron" + I18nUtil.getString("system_unvalid"));
} }
} else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE/* || scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/) { } else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE/* || scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/) {
if (jobInfo.getScheduleConf() == null) { if (jobInfo.getScheduleConf() == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")));
} }
try { try {
int fixSecond = Integer.valueOf(jobInfo.getScheduleConf()); int fixSecond = Integer.valueOf(jobInfo.getScheduleConf());
if (fixSecond < 1) { if (fixSecond < 1) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
} catch (Exception e) { } catch (Exception e) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
} }
// valid job // valid job
if (GlueTypeEnum.match(jobInfo.getGlueType()) == null) { if (GlueTypeEnum.match(jobInfo.getGlueType()) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_gluetype")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_gluetype") + I18nUtil.getString("system_unvalid")));
} }
if (GlueTypeEnum.BEAN==GlueTypeEnum.match(jobInfo.getGlueType()) && (jobInfo.getExecutorHandler()==null || jobInfo.getExecutorHandler().trim().length()==0) ) { if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType()) && (jobInfo.getExecutorHandler() == null || jobInfo.getExecutorHandler().trim().length() == 0)) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+"JobHandler") ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input") + "JobHandler"));
} }
// 》fix "\r" in shell // 》fix "\r" in shell
if (GlueTypeEnum.GLUE_SHELL==GlueTypeEnum.match(jobInfo.getGlueType()) && jobInfo.getGlueSource()!=null) { if (GlueTypeEnum.GLUE_SHELL == GlueTypeEnum.match(jobInfo.getGlueType()) && jobInfo.getGlueSource() != null) {
jobInfo.setGlueSource(jobInfo.getGlueSource().replaceAll("\r", "")); jobInfo.setGlueSource(jobInfo.getGlueSource().replaceAll("\r", ""));
} }
// valid advanced // valid advanced
if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) { if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorRouteStrategy")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorRouteStrategy") + I18nUtil.getString("system_unvalid")));
} }
if (MisfireStrategyEnum.match(jobInfo.getMisfireStrategy(), null) == null) { if (MisfireStrategyEnum.match(jobInfo.getMisfireStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("misfire_strategy")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("misfire_strategy") + I18nUtil.getString("system_unvalid")));
} }
if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) { if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorBlockStrategy")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorBlockStrategy") + I18nUtil.getString("system_unvalid")));
} }
// 》ChildJobId valid // 》ChildJobId valid
if (jobInfo.getChildJobId()!=null && jobInfo.getChildJobId().trim().length()>0) { if (jobInfo.getChildJobId() != null && jobInfo.getChildJobId().trim().length() > 0) {
String[] childJobIds = jobInfo.getChildJobId().split(","); String[] childJobIds = jobInfo.getChildJobId().split(",");
for (String childJobIdItem: childJobIds) { for (String childJobIdItem : childJobIds) {
if (childJobIdItem!=null && childJobIdItem.trim().length()>0 && isNumeric(childJobIdItem)) { if (childJobIdItem != null && childJobIdItem.trim().length() > 0 && isNumeric(childJobIdItem)) {
XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.parseInt(childJobIdItem)); XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.parseInt(childJobIdItem));
if (childJobInfo==null) { if (childJobInfo == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, return new ReturnT<String>(ReturnT.FAIL_CODE,
MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_not_found")), childJobIdItem)); MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_not_found")), childJobIdItem));
} }
} else { } else {
return new ReturnT<String>(ReturnT.FAIL_CODE, return new ReturnT<String>(ReturnT.FAIL_CODE,
MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_unvalid")), childJobIdItem)); MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_unvalid")), childJobIdItem));
} }
} }
// join , avoid "xxx,," // join , avoid "xxx,,"
String temp = ""; String temp = "";
for (String item:childJobIds) { for (String item : childJobIds) {
temp += item + ","; temp += item + ",";
} }
temp = temp.substring(0, temp.length()-1); temp = temp.substring(0, temp.length() - 1);
jobInfo.setChildJobId(temp); jobInfo.setChildJobId(temp);
} }
// add in db // add in db
jobInfo.setAddTime(new Date()); jobInfo.setAddTime(new Date());
jobInfo.setUpdateTime(new Date()); jobInfo.setUpdateTime(new Date());
jobInfo.setGlueUpdatetime(new Date()); jobInfo.setGlueUpdatetime(new Date());
xxlJobInfoDao.save(jobInfo); xxlJobInfoDao.save(jobInfo);
if (jobInfo.getId() < 1) { if (jobInfo.getId() < 1) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_add")+I18nUtil.getString("system_fail")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_add") + I18nUtil.getString("system_fail")));
} }
return new ReturnT<String>(String.valueOf(jobInfo.getId())); return new ReturnT<String>(String.valueOf(jobInfo.getId()));
} }
private boolean isNumeric(String str){ private boolean isNumeric(String str) {
try { try {
int result = Integer.valueOf(str); int result = Integer.valueOf(str);
return true; return true;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
return false; return false;
} }
} }
@Override @Override
public ReturnT<String> update(XxlJobInfo jobInfo) { public ReturnT<String> update(XxlJobInfo jobInfo) {
// valid base // valid base
if (jobInfo.getJobDesc()==null || jobInfo.getJobDesc().trim().length()==0) { if (jobInfo.getJobDesc() == null || jobInfo.getJobDesc().trim().length() == 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_jobdesc")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_jobdesc")));
} }
if (jobInfo.getAuthor()==null || jobInfo.getAuthor().trim().length()==0) { if (jobInfo.getAuthor() == null || jobInfo.getAuthor().trim().length() == 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_author")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_field_author")));
} }
// valid trigger // valid trigger
ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(jobInfo.getScheduleType(), null); ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(jobInfo.getScheduleType(), null);
if (scheduleTypeEnum == null) { if (scheduleTypeEnum == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
if (scheduleTypeEnum == ScheduleTypeEnum.CRON) { if (scheduleTypeEnum == ScheduleTypeEnum.CRON) {
if (jobInfo.getScheduleConf()==null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) { if (jobInfo.getScheduleConf() == null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron"+I18nUtil.getString("system_unvalid") ); return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron" + I18nUtil.getString("system_unvalid"));
} }
} else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE /*|| scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/) { } else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE /*|| scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/) {
if (jobInfo.getScheduleConf() == null) { if (jobInfo.getScheduleConf() == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
try { try {
int fixSecond = Integer.valueOf(jobInfo.getScheduleConf()); int fixSecond = Integer.valueOf(jobInfo.getScheduleConf());
if (fixSecond < 1) { if (fixSecond < 1) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
} catch (Exception e) { } catch (Exception e) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
} }
// valid advanced // valid advanced
if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) { if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorRouteStrategy")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorRouteStrategy") + I18nUtil.getString("system_unvalid")));
} }
if (MisfireStrategyEnum.match(jobInfo.getMisfireStrategy(), null) == null) { if (MisfireStrategyEnum.match(jobInfo.getMisfireStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("misfire_strategy")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("misfire_strategy") + I18nUtil.getString("system_unvalid")));
} }
if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) { if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorBlockStrategy")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorBlockStrategy") + I18nUtil.getString("system_unvalid")));
} }
// 》ChildJobId valid // 》ChildJobId valid
if (jobInfo.getChildJobId()!=null && jobInfo.getChildJobId().trim().length()>0) { if (jobInfo.getChildJobId() != null && jobInfo.getChildJobId().trim().length() > 0) {
String[] childJobIds = jobInfo.getChildJobId().split(","); String[] childJobIds = jobInfo.getChildJobId().split(",");
for (String childJobIdItem: childJobIds) { for (String childJobIdItem : childJobIds) {
if (childJobIdItem!=null && childJobIdItem.trim().length()>0 && isNumeric(childJobIdItem)) { if (childJobIdItem != null && childJobIdItem.trim().length() > 0 && isNumeric(childJobIdItem)) {
XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.parseInt(childJobIdItem)); XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.parseInt(childJobIdItem));
if (childJobInfo==null) { if (childJobInfo == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, return new ReturnT<String>(ReturnT.FAIL_CODE,
MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_not_found")), childJobIdItem)); MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_not_found")), childJobIdItem));
} }
} else { } else {
return new ReturnT<String>(ReturnT.FAIL_CODE, return new ReturnT<String>(ReturnT.FAIL_CODE,
MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_unvalid")), childJobIdItem)); MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId") + "({0})" + I18nUtil.getString("system_unvalid")), childJobIdItem));
} }
} }
// join , avoid "xxx,," // join , avoid "xxx,,"
String temp = ""; String temp = "";
for (String item:childJobIds) { for (String item : childJobIds) {
temp += item + ","; temp += item + ",";
} }
temp = temp.substring(0, temp.length()-1); temp = temp.substring(0, temp.length() - 1);
jobInfo.setChildJobId(temp); jobInfo.setChildJobId(temp);
} }
// group valid // group valid
XxlJobGroup jobGroup = xxlJobGroupDao.load(jobInfo.getJobGroup()); XxlJobGroup jobGroup = xxlJobGroupDao.load(jobInfo.getJobGroup());
if (jobGroup == null) { if (jobGroup == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_jobgroup")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_jobgroup") + I18nUtil.getString("system_unvalid")));
} }
// stage job info // stage job info
XxlJobInfo exists_jobInfo = xxlJobInfoDao.loadById(jobInfo.getId()); XxlJobInfo exists_jobInfo = xxlJobInfoDao.loadById(jobInfo.getId());
if (exists_jobInfo == null) { if (exists_jobInfo == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_id")+I18nUtil.getString("system_not_found")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_id") + I18nUtil.getString("system_not_found")));
} }
// next trigger time (5s后生效避开预读周期) // next trigger time (5s后生效避开预读周期)
long nextTriggerTime = exists_jobInfo.getTriggerNextTime(); long nextTriggerTime = exists_jobInfo.getTriggerNextTime();
boolean scheduleDataNotChanged = jobInfo.getScheduleType().equals(exists_jobInfo.getScheduleType()) && jobInfo.getScheduleConf().equals(exists_jobInfo.getScheduleConf()); boolean scheduleDataNotChanged = jobInfo.getScheduleType().equals(exists_jobInfo.getScheduleType()) && jobInfo.getScheduleConf().equals(exists_jobInfo.getScheduleConf());
if (exists_jobInfo.getTriggerStatus() == 1 && !scheduleDataNotChanged) { if (exists_jobInfo.getTriggerStatus() == 1 && !scheduleDataNotChanged) {
try { try {
Date nextValidTime = JobScheduleHelper.generateNextValidTime(jobInfo, new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS)); Date nextValidTime = JobScheduleHelper.generateNextValidTime(jobInfo, new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));
if (nextValidTime == null) { if (nextValidTime == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
nextTriggerTime = nextValidTime.getTime(); nextTriggerTime = nextValidTime.getTime();
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) ); return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
} }
} }
exists_jobInfo.setJobGroup(jobInfo.getJobGroup()); exists_jobInfo.setJobGroup(jobInfo.getJobGroup());
exists_jobInfo.setJobDesc(jobInfo.getJobDesc()); exists_jobInfo.setJobDesc(jobInfo.getJobDesc());
exists_jobInfo.setAuthor(jobInfo.getAuthor()); exists_jobInfo.setAuthor(jobInfo.getAuthor());
exists_jobInfo.setAlarmEmail(jobInfo.getAlarmEmail()); exists_jobInfo.setAlarmEmail(jobInfo.getAlarmEmail());
exists_jobInfo.setScheduleType(jobInfo.getScheduleType()); exists_jobInfo.setScheduleType(jobInfo.getScheduleType());
exists_jobInfo.setScheduleConf(jobInfo.getScheduleConf()); exists_jobInfo.setScheduleConf(jobInfo.getScheduleConf());
exists_jobInfo.setMisfireStrategy(jobInfo.getMisfireStrategy()); exists_jobInfo.setMisfireStrategy(jobInfo.getMisfireStrategy());
exists_jobInfo.setExecutorRouteStrategy(jobInfo.getExecutorRouteStrategy()); exists_jobInfo.setExecutorRouteStrategy(jobInfo.getExecutorRouteStrategy());
exists_jobInfo.setExecutorHandler(jobInfo.getExecutorHandler()); exists_jobInfo.setExecutorHandler(jobInfo.getExecutorHandler());
exists_jobInfo.setExecutorParam(jobInfo.getExecutorParam()); exists_jobInfo.setExecutorParam(jobInfo.getExecutorParam());
exists_jobInfo.setExecutorBlockStrategy(jobInfo.getExecutorBlockStrategy()); exists_jobInfo.setExecutorBlockStrategy(jobInfo.getExecutorBlockStrategy());
exists_jobInfo.setExecutorTimeout(jobInfo.getExecutorTimeout()); exists_jobInfo.setExecutorTimeout(jobInfo.getExecutorTimeout());
exists_jobInfo.setExecutorFailRetryCount(jobInfo.getExecutorFailRetryCount()); exists_jobInfo.setExecutorFailRetryCount(jobInfo.getExecutorFailRetryCount());
exists_jobInfo.setChildJobId(jobInfo.getChildJobId()); exists_jobInfo.setChildJobId(jobInfo.getChildJobId());
exists_jobInfo.setTriggerNextTime(nextTriggerTime); exists_jobInfo.setTriggerNextTime(nextTriggerTime);
exists_jobInfo.setUpdateTime(new Date()); exists_jobInfo.setUpdateTime(new Date());
xxlJobInfoDao.update(exists_jobInfo); xxlJobInfoDao.update(exists_jobInfo);
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
@Override @Override
public ReturnT<String> remove(int id) { public ReturnT<String> remove(int id) {
XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id); XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id);
if (xxlJobInfo == null) { if (xxlJobInfo == null) {
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
xxlJobInfoDao.delete(id); xxlJobInfoDao.delete(id);
xxlJobLogDao.delete(id); xxlJobLogDao.delete(id);
xxlJobLogGlueDao.deleteByJobId(id); xxlJobLogGlueDao.deleteByJobId(id);
return ReturnT.SUCCESS; return ReturnT.SUCCESS;
} }
@Override @Override
public ReturnT<String> start(int id) { public ReturnT<String> start(int id) {
XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id);
// valid
ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(xxlJobInfo.getScheduleType(), ScheduleTypeEnum.NONE);
if (ScheduleTypeEnum.NONE == scheduleTypeEnum) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type_none_limit_start")) );
}
// next trigger time (5s后生效避开预读周期)
long nextTriggerTime = 0;
try {
Date nextValidTime = JobScheduleHelper.generateNextValidTime(xxlJobInfo, new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));
if (nextValidTime == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
nextTriggerTime = nextValidTime.getTime();
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
xxlJobInfo.setTriggerStatus(1);
xxlJobInfo.setTriggerLastTime(0);
xxlJobInfo.setTriggerNextTime(nextTriggerTime);
xxlJobInfo.setUpdateTime(new Date());
xxlJobInfoDao.update(xxlJobInfo);
return ReturnT.SUCCESS;
}
@Override
public ReturnT<String> stop(int id) {
XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id); XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id);
xxlJobInfo.setTriggerStatus(0); // valid
xxlJobInfo.setTriggerLastTime(0); ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(xxlJobInfo.getScheduleType(), ScheduleTypeEnum.NONE);
xxlJobInfo.setTriggerNextTime(0); if (ScheduleTypeEnum.NONE == scheduleTypeEnum) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type_none_limit_start")));
}
xxlJobInfo.setUpdateTime(new Date()); // next trigger time (5s后生效避开预读周期)
xxlJobInfoDao.update(xxlJobInfo); long nextTriggerTime = 0;
return ReturnT.SUCCESS; try {
} Date nextValidTime = JobScheduleHelper.generateNextValidTime(xxlJobInfo, new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));
if (nextValidTime == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
}
nextTriggerTime = nextValidTime.getTime();
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")));
}
@Override xxlJobInfo.setTriggerStatus(1);
public Map<String, Object> dashboardInfo() { xxlJobInfo.setTriggerLastTime(0);
xxlJobInfo.setTriggerNextTime(nextTriggerTime);
int jobInfoCount = xxlJobInfoDao.findAllCount(); xxlJobInfo.setUpdateTime(new Date());
int jobLogCount = 0; xxlJobInfoDao.update(xxlJobInfo);
int jobLogSuccessCount = 0; return ReturnT.SUCCESS;
XxlJobLogReport xxlJobLogReport = xxlJobLogReportDao.queryLogReportTotal(); }
if (xxlJobLogReport != null) {
jobLogCount = xxlJobLogReport.getRunningCount() + xxlJobLogReport.getSucCount() + xxlJobLogReport.getFailCount();
jobLogSuccessCount = xxlJobLogReport.getSucCount();
}
// executor count @Override
Set<String> executorAddressSet = new HashSet<String>(); public ReturnT<String> stop(int id) {
List<XxlJobGroup> groupList = xxlJobGroupDao.findAll(); XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id);
if (groupList!=null && !groupList.isEmpty()) { xxlJobInfo.setTriggerStatus(0);
for (XxlJobGroup group: groupList) { xxlJobInfo.setTriggerLastTime(0);
if (group.getRegistryList()!=null && !group.getRegistryList().isEmpty()) { xxlJobInfo.setTriggerNextTime(0);
executorAddressSet.addAll(group.getRegistryList());
}
}
}
int executorCount = executorAddressSet.size(); xxlJobInfo.setUpdateTime(new Date());
xxlJobInfoDao.update(xxlJobInfo);
return ReturnT.SUCCESS;
}
Map<String, Object> dashboardMap = new HashMap<String, Object>(); @Override
dashboardMap.put("jobInfoCount", jobInfoCount); public Map<String, Object> dashboardInfo() {
dashboardMap.put("jobLogCount", jobLogCount);
dashboardMap.put("jobLogSuccessCount", jobLogSuccessCount);
dashboardMap.put("executorCount", executorCount);
return dashboardMap;
}
@Override int jobInfoCount = xxlJobInfoDao.findAllCount();
public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) { int jobLogCount = 0;
int jobLogSuccessCount = 0;
XxlJobLogReport xxlJobLogReport = xxlJobLogReportDao.queryLogReportTotal();
if (xxlJobLogReport != null) {
jobLogCount = xxlJobLogReport.getRunningCount() + xxlJobLogReport.getSucCount() + xxlJobLogReport.getFailCount();
jobLogSuccessCount = xxlJobLogReport.getSucCount();
}
// process // executor count
List<String> triggerDayList = new ArrayList<String>(); Set<String> executorAddressSet = new HashSet<String>();
List<Integer> triggerDayCountRunningList = new ArrayList<Integer>(); List<XxlJobGroup> groupList = xxlJobGroupDao.findAll();
List<Integer> triggerDayCountSucList = new ArrayList<Integer>();
List<Integer> triggerDayCountFailList = new ArrayList<Integer>();
int triggerCountRunningTotal = 0;
int triggerCountSucTotal = 0;
int triggerCountFailTotal = 0;
List<XxlJobLogReport> logReportList = xxlJobLogReportDao.queryLogReport(startDate, endDate); if (groupList != null && !groupList.isEmpty()) {
for (XxlJobGroup group : groupList) {
if (group.getRegistryList() != null && !group.getRegistryList().isEmpty()) {
executorAddressSet.addAll(group.getRegistryList());
}
}
}
if (logReportList!=null && logReportList.size()>0) { int executorCount = executorAddressSet.size();
for (XxlJobLogReport item: logReportList) {
String day = DateUtil.formatDate(item.getTriggerDay());
int triggerDayCountRunning = item.getRunningCount();
int triggerDayCountSuc = item.getSucCount();
int triggerDayCountFail = item.getFailCount();
triggerDayList.add(day); Map<String, Object> dashboardMap = new HashMap<String, Object>();
triggerDayCountRunningList.add(triggerDayCountRunning); dashboardMap.put("jobInfoCount", jobInfoCount);
triggerDayCountSucList.add(triggerDayCountSuc); dashboardMap.put("jobLogCount", jobLogCount);
triggerDayCountFailList.add(triggerDayCountFail); dashboardMap.put("jobLogSuccessCount", jobLogSuccessCount);
dashboardMap.put("executorCount", executorCount);
return dashboardMap;
}
triggerCountRunningTotal += triggerDayCountRunning; @Override
triggerCountSucTotal += triggerDayCountSuc; public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) {
triggerCountFailTotal += triggerDayCountFail;
}
} else {
for (int i = -6; i <= 0; i++) {
triggerDayList.add(DateUtil.formatDate(DateUtil.addDays(new Date(), i)));
triggerDayCountRunningList.add(0);
triggerDayCountSucList.add(0);
triggerDayCountFailList.add(0);
}
}
Map<String, Object> result = new HashMap<String, Object>(); // process
result.put("triggerDayList", triggerDayList); List<String> triggerDayList = new ArrayList<String>();
result.put("triggerDayCountRunningList", triggerDayCountRunningList); List<Integer> triggerDayCountRunningList = new ArrayList<Integer>();
result.put("triggerDayCountSucList", triggerDayCountSucList); List<Integer> triggerDayCountSucList = new ArrayList<Integer>();
result.put("triggerDayCountFailList", triggerDayCountFailList); List<Integer> triggerDayCountFailList = new ArrayList<Integer>();
int triggerCountRunningTotal = 0;
int triggerCountSucTotal = 0;
int triggerCountFailTotal = 0;
result.put("triggerCountRunningTotal", triggerCountRunningTotal); List<XxlJobLogReport> logReportList = xxlJobLogReportDao.queryLogReport(startDate, endDate);
result.put("triggerCountSucTotal", triggerCountSucTotal);
result.put("triggerCountFailTotal", triggerCountFailTotal);
return new ReturnT<Map<String, Object>>(result); if (logReportList != null && logReportList.size() > 0) {
} for (XxlJobLogReport item : logReportList) {
String day = DateUtil.formatDate(item.getTriggerDay());
int triggerDayCountRunning = item.getRunningCount();
int triggerDayCountSuc = item.getSucCount();
int triggerDayCountFail = item.getFailCount();
triggerDayList.add(day);
triggerDayCountRunningList.add(triggerDayCountRunning);
triggerDayCountSucList.add(triggerDayCountSuc);
triggerDayCountFailList.add(triggerDayCountFail);
triggerCountRunningTotal += triggerDayCountRunning;
triggerCountSucTotal += triggerDayCountSuc;
triggerCountFailTotal += triggerDayCountFail;
}
} else {
for (int i = -6; i <= 0; i++) {
triggerDayList.add(DateUtil.formatDate(DateUtil.addDays(new Date(), i)));
triggerDayCountRunningList.add(0);
triggerDayCountSucList.add(0);
triggerDayCountFailList.add(0);
}
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("triggerDayList", triggerDayList);
result.put("triggerDayCountRunningList", triggerDayCountRunningList);
result.put("triggerDayCountSucList", triggerDayCountSucList);
result.put("triggerDayCountFailList", triggerDayCountFailList);
result.put("triggerCountRunningTotal", triggerCountRunningTotal);
result.put("triggerCountSucTotal", triggerCountSucTotal);
result.put("triggerCountFailTotal", triggerCountFailTotal);
return new ReturnT<Map<String, Object>>(result);
}
} }

View File

@ -1,6 +1,6 @@
admin_name=Scheduling Center admin_name=Scheduling Center
admin_name_full=Distributed Task Scheduling Platform XXL-JOB admin_name_full=Distributed Task Scheduling Platform XXL-JOB
admin_version=2.3.0 admin_version=2.3.1
admin_i18n=en admin_i18n=en
## system ## system

View File

@ -1,6 +1,6 @@
admin_name=任务调度中心 admin_name=任务调度中心
admin_name_full=分布式任务调度平台XXL-JOB admin_name_full=分布式任务调度平台XXL-JOB
admin_version=2.3.0 admin_version=2.3.1
admin_i18n= admin_i18n=
## system ## system

View File

@ -1,6 +1,6 @@
admin_name=任務調度中心 admin_name=任務調度中心
admin_name_full=分布式任務調度平臺XXL-JOB admin_name_full=分布式任務調度平臺XXL-JOB
admin_version=2.3.0 admin_version=2.3.1
admin_i18n= admin_i18n=
## system ## system