01 | 问题描述
- 在ssm框架中配置定时任务时发现,当项目启动时,定时任务只能执行一次,随后便静止不动。
02 | 原因
- 未写清定时扫描的包。需在applicationContext.xml中的追加配置如下:
<context:component-scan base-package="com.how2java.file.controller"/> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <task:scheduler id="myScheduler" pool-size="10"/>
03 | SSM定时任务配置流程如下:
1.在spring配置文件applicationContext.xml中添加xmlns和xsd
- xmlns需要添加的内容:
xmlns:task="http://www.springframework.org/schema/task"
- xsd需要添加的内容:
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
- 在applicationContext.xml中添加代码
<!--cron定时器配置--> <task:annotation-driven /> <context:component-scan base-package="com.how2java.file.controller"/> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <task:scheduler id="myScheduler" pool-size="10"/>
- 在定时触发的方法上添加注解@Scheduled, 这里是在Controller中添加
@RequestMapping("/file_clock")
@Scheduled(fixedRate = 5000) //每隔5秒执行一次
public void clock(){
List<Filems> ps = filemsService.list();
for(int i = 0 ; i < ps.size() ; i++) {
System.out.println(ps.get(i));
if (ps.get(i) != null){
System.out.println("F:\\upload111\\" + ps.get(i).getFileUrl());
File file = new File("F:\\upload111\\" + ps.get(i).getFileUrl());
if (!file.exists()) { //用来测试此路径名表示的文件或目录是否存在
System.out.println("文件不存在,终止运行!");
} else {
System.out.println("文件存在");
}
}
}
// return "admin/clock"; 注意:该定时触发的函数返回值必须是void否则Spring启动会报错。
}
- tip:corn表达式生成器地址:https://cron.qqe2.com/
- 指路:SSM手动开启和关闭定时任务