Cron to run at 12:00 AM every day using Spring Scheduler

Deepak Tripathi picture Deepak Tripathi · Oct 1, 2015 · Viewed 8.3k times · Source

I am trying to execute a method every day for which I have added scheduler using Spring but its not getting executed.

<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"/>

Answer

Alexandre Jacob picture Alexandre Jacob · Oct 1, 2015

To me, the cron expression you are looking for is : 0 0 12 * * ?

Here is a working sample for you :

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>

Task 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());
    }
}