Cron每天凌晨12点使用Spring Scheduler运行

时间:2015-10-01 11:04:40

标签: spring cron cronexpression spring-scheduled

我正在尝试每天执行一个方法,我已经使用Spring添加了调度程序,但它没有被执行。

<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="logDeletionTask" method="deleteExpiredLogs" cron="0 0 0 * * ?" />
</task:scheduled-tasks>
<task:scheduler pool-size="25" id="myScheduler"/>

1 个答案:

答案 0 :(得分:1)

对我而言,您正在寻找的cron表达式为:0 0 12 * * ?

以下是适合您的工作示例:

applicationContext.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" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <bean id="logDeletionTask" class="task.Task" />

    <task:scheduled-tasks scheduler="myScheduler">
        <task:scheduled ref="logDeletionTask" method="deleteExpiredLogs" cron="0 0 12 * * ?" />
    </task:scheduled-tasks>

    <task:scheduler pool-size="25" id="myScheduler"/>
</beans>

任务bean:

package task;

import java.util.Date;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Task {

    public static void main(String[] args) throws InterruptedException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        while (true) {
            Thread.sleep(1000);
        }
    }

    public void deleteExpiredLogs() {
        System.out.println(new Date());
    }
}