Spring 预定注释是如何工作的

Spring Scheduled annotation how does it work

我在 java.That 中创建了一个函数,函数应该 运行 每天半夜

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

但我没有像 expected.Sometime 它执行的那样工作,有时 not.Any 解决这个问题。

Spring版本为4

你不应该为此使用静态方法。尝试使用以下代码:

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