Spring Scheduled annotation how does it work

2019-08-15 07:45发布

问题:

I have created a function in java.That function should run on every day mid night

//My function this function is within UpdateService Class
@Scheduled(cron = "0 0 0 * * ?")
public static void UpdateFn() {
    try {
        System.out.println("-----------Background Task Running----------------");
        //code to update some data every day
        System.out.println("-----------Background Task Ending----------------");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//My xml configuration
 <task:annotation-driven />
    <bean id="UpdateTask" class="com.ss.utility.UpdateService"></bean>
  </beans>

But i not working as expected.Sometime it executed and sometime not.Any solution for this.

Spring version is 4

回答1:

You shoundn't use static method for this. Try to use following code:

@Scheduled(cron = "0 0 0 * * ?")
public void UpdateFn() {
    try {
        System.out.println("-----------Background Task Running----------------");
        //code to update some data every day
        System.out.println("-----------Background Task Ending----------------");
    } catch (Exception e) {
        e.printStackTrace();
    }
}