春天如何使用@scheduled批注

时间:2019-04-01 11:10:16

标签: java spring cron

我必须读取创建的文件(视频)的时间,如果文件时间超过3天,则必须删除文件。为此,我在春季使用了@scheduled注解。但是,当我运行该应用程序时,该删除代码无法正常工作。我已经在spring xml文件中配置了xmlns:task="http://www.springframework.org/schema/task" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd <task:annotation-driven />。它显示架构参考4:读取失败。因此,我决定使用完整的注释。 java版本是7,spring版本是4.2.2。我已经在下午4点设置了cron表达式,并在3.58 PM运行了应用程序。什么都没执行。我想念什么。什么是放置此代码的最佳软件包(控制器/服务/辅助逻辑)。而且我也想知道如何实现DELETE方法。这是我删除视频的代码

package com.test.logic;
import java.io.File;
import java.util.Date;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.sun.xml.internal.ws.developer.SchemaValidation;

@Component
@EnableScheduling
public class VideoDelete {
    @Scheduled(cron="* 1-15 16 * * * *")
    public void deleteVideo(){
    System.out.println("========> $$$$$$ scheduler method is executed $$$$$ <==========");
        long presentTime=System.currentTimeMillis();
        Date presentDate=new Date(presentTime);
        File file=new File("E://videorecording1");
        File[] fileList=file.listFiles();
        for (File files : fileList){
            if (files.isFile()){
                long filecreatedtime=files.lastModified();
                Date fileDate=new Date(filecreatedtime);
                long difference = presentDate.getTime() - fileDate.getTime();
                long hoursDifference = difference / (60 * 60 * 1000);
                if(hoursDifference >= 72)
                    files.delete();
            }
        }
}
}

3 个答案:

答案 0 :(得分:2)

Spring Scheduler的cron仅允许6种触发器。

根据官方文档:

  

类似cron的表达式,将通常的UN * X定义扩展为   包含触发器   *在秒以及分钟,小时,每月的某天,每月的某天和一周的某天。

要支持7个触发器(包括年份),您必须使用Quartz:https://www.quartz-scheduler.org/

在您当前的情况下,请尝试以下操作:

(cron = "0 0 16 * * ?")

答案 1 :(得分:1)

我认为您最好尝试使用cron表达式"*/10 * * * * *,这基本上意味着方法将每10秒执行一次,没有小时/日期/天的限制。 这样,您将看到spring配置本身或文件权限是否有问题。

答案 2 :(得分:0)

我找到了解决方案。原因是spring容器无法将VideoDelete类识别为spring bean。所以我已经用@controller注释了它,现在工作正常。