Spring计划任务

每次项目启动时的计划任务

1、src/main/resources的springframework追加

spring-custom-bean.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="io.deolin.util.FolderInitializer" init-method="init" />

</beans>

 

2、工具类

public class ContextPathInitializer {

    Logger LOG = LogManager.getLogger(ContextPathInitializer.class);

    public void init() {
        initContextPathInDisk();
    }

    private void initContextPathInDisk() {
        File uploadImageFloder = new File(BasicsConstant.UPLOAD_IMAGE_FLODER_PATH);
        if (!uploadImageFloder.exists()) {
            LOG.warn("目录[" + BasicsConstant.UPLOAD_IMAGE_FLODER_PATH + "]不存在,自动创建该目录");
            uploadImageFloder.mkdirs();
        }
    }

}

 

每隔一段时间或固定时间点的计划任务

1、pom.xml追加

spring-support

quartz

 

2、src/main/resources的springframework追加

spring-quartz.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 任务,需要向targetObject注入工具类,需要向targetMehtod注入工具方法名 -->
    <bean id="ExcessFileClearJob"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <bean class="io.deolin.util.ExcessFileClearer" />
        </property>
        <property name="targetMethod" value="clearExcessUploadImage" />
        <property name="concurrent" value="false" />
    </bean>
    <!-- 触发器,决定多久执行一次ExcessFileClearJob -->
    <bean id="cronTrigger"
        class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="ExcessFileClearJob" />
        <property name="cronExpression" value="0 0 0 ? * MON" /><!-- 每周一00:00 -->
    </bean>
    <!-- 测试用触发器 -->
    <bean id="simpleTrigger"
        class="org.springframework.scheduling.quartz.SimpleTriggerBean">
        <property name="jobDetail" ref="ExcessFileClearJob" />
        <property name="startDelay" value="0" />
        <property name="repeatInterval" value="5000" /><!-- 每5秒一次 -->
    </bean>
    <!-- 定时器 -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <!-- <ref bean="simpleTrigger" /> -->
                <ref bean="cronTrigger" />
            </list>
        </property>
    </bean>
</beans>

 

3、工具类

public class ExcessFileClearer {

    public void clearExcessUploadImage() {
        // 清除多余的上传文件,省略
    }

}

 

posted @ 2017-09-03 17:07  Deolin  阅读(247)  评论(0编辑  收藏  举报