JarTaskInvoke.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2021-2025, LXQ All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. *
  7. * Redistributions of source code must retain the above copyright notice,
  8. * this list of conditions and the following disclaimer.
  9. * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * Neither the name of the com developer nor the names of its
  13. * contributors may be used to endorse or promote products derived from
  14. * this software without specific prior written permission.
  15. * Author: LXQ (609827073@qq.com)
  16. */
  17. package com.lxq.daemon.quartz.util;
  18. import cn.hutool.core.util.StrUtil;
  19. import com.lxq.daemon.quartz.exception.TaskException;
  20. import com.lxq.daemon.quartz.entity.SysJob;
  21. import lombok.extern.slf4j.Slf4j;
  22. import org.springframework.stereotype.Component;
  23. import java.io.File;
  24. import java.io.IOException;
  25. import java.util.ArrayList;
  26. import java.util.List;
  27. /**
  28. * 定时任务可执行jar反射实现
  29. *
  30. * @author LXQ
  31. */
  32. @Slf4j
  33. @Component("jarTaskInvoke")
  34. public class JarTaskInvoke implements ITaskInvoke {
  35. @Override
  36. public void invokeMethod(SysJob sysJob) throws TaskException {
  37. ProcessBuilder processBuilder = new ProcessBuilder();
  38. File jar = new File(sysJob.getExecutePath());
  39. processBuilder.directory(jar.getParentFile());
  40. List<String> commands = new ArrayList<>();
  41. commands.add("java");
  42. commands.add("-jar");
  43. commands.add(sysJob.getExecutePath());
  44. if (StrUtil.isNotEmpty(sysJob.getMethodParamsValue())) {
  45. commands.add(sysJob.getMethodParamsValue());
  46. }
  47. processBuilder.command(commands);
  48. try {
  49. processBuilder.start();
  50. }
  51. catch (IOException e) {
  52. log.error("定时任务jar反射执行异常,执行任务:{}", sysJob.getExecutePath());
  53. throw new TaskException("定时任务jar反射执行异常,执行任务:" + sysJob.getExecutePath());
  54. }
  55. }
  56. }