SSM框架定时任务只执行一次

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"/>
    
  1. 在定时触发的方法上添加注解@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启动会报错。
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值