在以往的 Tomcat 项目中,一直习惯用 Ant 打包,使用 build.xml 配置,通过 ant -buildfile 的方式在机器上执行定时任务。虽然 Spring 本身支持定时任务,但都是服务一直运行时支持。其实在项目中,大多数定时任务,还是借助 Linux Crontab 来支持,需要时运行即可,不需要一直占用机器资源。但 Spring Boot 项目或者普通的 jar 项目,就没这么方便了。
Spring Boot 提供了类似 CommandLineRunner 的方式,很好的执行常驻任务;也可以借助 ApplicationListener 和 ContextRefreshedEvent 等事件来做很多事情。借助该容器事件,一样可以做到类似 Ant 运行的方式来运行定时任务,当然需要做一些项目改动。
1. 监听目标对象
借助容器刷新事件来监听目标对象即可,可以认为,定时任务其实每次只是执行一种操作而已。
比如这是一个写好的例子,注意不要直接用 @Service 将其放入容器中,除非容器本身没有其它自动运行的事件。
package com.github.zhgxun.learn.common.task; import com.github.zhgxun.learn.common.task.annotation.ScheduleTask; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @Slf4j public class TaskApplicationListener implements ApplicationListener{ private static final String SPRING_TASK_CLASS = "spring.task.class"; private static final int SUPPORT_METHOD_COUNT = 1; private ApplicationContext context; @Override @SuppressWarnings("unchecked") public void onApplicationEvent(ContextRefreshedEvent event) { context = event.getApplicationContext(); // 不存在时可能为正常的容器启动运行, 无需关心 String taskClass = System.getProperty(SPRING_TASK_CLASS); log.info("ScheduleTask spring task Class: {}", taskClass); if (taskClass != null) { try { // 获取类字节码文件 Class clazz = findClass(taskClass); // 尝试从内容上下文中获取已加载的目标类对象实例, 这个类实例是已经加载到容器内的对象实例, 即可以获取类的信息 Object object = context.getBean(clazz); Method method = findMethod(object); log.info("start to run task Class: {}, Method: {}", taskClass, method.getName()); invoke(method, object); } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } finally { // 需要确保容器正常出发停止事件, 否则容器会僵尸卡死 shutdown(); } } } private Class findClass(String clazz) throws ClassNotFoundException { return Class.forName(clazz); } private Method findMethod(Object object) { Method[] methods = object.getClass().getDeclaredMethods(); List schedules = Stream.of(methods) .filter(method -> method.isAnnotationPresent(ScheduleTask.class)) .collect(Collectors.toList()); if (schedules.size() != SUPPORT_METHOD_COUNT) { throw new IllegalStateException("only one method should be annotated with @ScheduleTask, but found " + schedules.size()); } return schedules.get(0); } private void invoke(Method method, Object object) throws IllegalAccessException, InvocationTargetException { method.invoke(object); } private void shutdown() { log.info("shutdown ..."); System.exit(SpringApplication.exit(context)); } }
其实该处仅需要启动执行即可,容器启动完毕事件也是可以的。
2. 标识目标方法
目标方法的标识,最方便的是使用注解标注。
package com.github.zhgxun.learn.common.task.annotation;
import java.lang.annotation.documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@documented
public @interface ScheduleTask {
}
3. 编写任务
package com.github.zhgxun.learn.task;
import com.github.zhgxun.learn.common.task.annotation.ScheduleTask;
import com.github.zhgxun.learn.service.first.LaunchInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class TestTask {
@Autowired
private LaunchInfoService launchInfoService;
@ScheduleTask
public void test() {
log.info("Start task ...");
log.info("LaunchInfoList: {}", launchInfoService.findAll());
log.info("模拟启动线程操作");
for (int i = 0; i < 5; i++) {
new MyTask(i).start();
}
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyTask extends Thread {
private int i;
private int j;
private String s;
public MyTask(int i) {
this.i = i;
}
@Override
public void run() {
super.run();
System.out.println("第 " + i + " 个线程启动..." + Thread.currentThread().getName());
if (i == 2) {
throw new RuntimeException("模拟运行时异常");
}
if (i == 3) {
// 除数不为0
int a = i / j;
}
// 未对字符串对象赋值, 获取长度报空指针错误
if (i == 4) {
System.out.println(s.length());
}
}
}
4. 启动改造
启动时需要做一些调整,即跟普通的启动区分开。这也是为什么不要把监听目标对象直接放入容器中的原因,在这里显示添加到容器中,这样就不影响项目中类似 CommandLineRunner 的功能,毕竟这种功能是容器启动完毕就能运行的。如果要改造,会涉及到很多硬编码。
package com.github.zhgxun.learn;
import com.github.zhgxun.learn.common.task.TaskApplicationListener;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@SpringBootApplication
public class LearnApplication {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(LearnApplication.class);
// 根据启动注入参数判断是否为任务动作即可, 否则不干预启动
if (System.getProperty("spring.task.class") != null) {
builder.listeners(new TaskApplicationListener()).run(args);
} else {
builder.run(args);
}
}
}
5. 启动注入
-Dspring.task.class 即是启动注入标识,当然这个标识不要跟默认的参数混淆,需要区分开,否则可能始终获取到系统参数,而无法获取用户参数。
java -Dspring.task.class=com.github.zhgxun.learn.task.TestTask -jar target/learn.jar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



