Springboot定时任务

来源:互联网 发布:贵港问政网络平台 编辑:程序博客网 时间:2024/06/14 02:51

1、新建定时任务类(不包含业务逻辑)

新建一个类,添加@Component注解

import java.io.File;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class autoTimeJob {    private static Logger log=LoggerFactory.getLogger(autoTimeJob.class);    @Value("${uploadFilePath}")//在配置文件里配置的路径    private String fileDir;    @Scheduled(cron="0 0/1 3-22 * * ?")    public void cleanPath(){        String path=fileDir+"/data/picSearch/";        File file=new File(path);        boolean flag=false;        if(file.exists()){            try{                flag=deleteDir(file);                log.info("清空文件夹【"+path+"】"+(flag==false?"失败":"成功"));            }catch(Exception e){                log.info("清空文件夹【"+path+"】失败;"+e.getMessage());            }        }        flag=file.mkdir();        log.info("新建文件夹【"+path+"】"+(flag==false?"失败":"成功"));    }    private  boolean deleteDir(File dir) {        if (dir.isDirectory()) {            String[] children = dir.list();            //递归删除目录中的子目录下            for (int i=0; i<children.length; i++) {                boolean success = deleteDir(new File(dir, children[i]));                if (!success) {                    return false;                }            }        }        // 目录此时为空,可以删除        return dir.delete();    }}

在springboot启动类添加@EnableScheduling,允许支持schedule。

import javax.servlet.MultipartConfigElement;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.builder.SpringApplicationBuilder;import org.springframework.boot.web.servlet.MultipartConfigFactory;import org.springframework.boot.web.support.SpringBootServletInitializer;import org.springframework.context.annotation.Bean;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublic class Application extends SpringBootServletInitializer{    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

@Scheduled(cron=”0 0/1 3-22 * * ?”)注解说明:
cron一共有7位,最后一位是年,可以留空,所以我们可以写6位:

* 第一位,表示秒,取值0-59* 第二位,表示分,取值0-59* 第三位,表示小时,取值0-23* 第四位,日期天/日,取值1-31* 第五位,日期月份,取值1-12* 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思; 另外:1表示星期天,2表示星期一。* 第7为,年份,可以留空

cron中,还有一些特殊的符号,含义如下:

(*)星号:可以理解为每的意思,每秒,每分,每天,每月,每年...(?)问号:问号只能出现在日期和星期这两个位置,表示这个位置的值不确定。同时:日期和星期是两个相互排斥的元素,通过问号来表明不指定值。比如,110日,比如是星期1,如果在星期的位置是另指定星期二,就前后冲突矛盾了。(-)减号:表达一个范围,如在小时字段中使用“3-22”,则表示从322点(,)逗号:表达一个列表值,如在星期字段中使用“1,2,4”,则表示星期天,星期一,星期三(/)斜杠:如:x/y,x是开始值,y是步长,比如在第一位(秒) 0/15就是,从0秒开始,每15秒,最后就是015304560    另:*/y,等同于0/y

注:此处为单线程任务

原创粉丝点击