简体   繁体   English

Spring @Scheduled 注解按顺序为同一时间实例执行

[英]Spring @Scheduled annotation execute in order for the same time instance

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
public class Scheduler {

    @Scheduled(cron = "0 */1 * * * ?")
    public void method1()  {
        System.out.println("1");
    }

    @Scheduled(cron = "0 */2 * * * ?")
    public void method2(){
        System.out.println("2");
    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void method3()  {
        System.out.println("3");
    }

    @Scheduled(cron = "0 */2 * * * ?")
    public void method4()  {
        System.out.println("4");
    }
}

Actual Output:实际输出:

1
3

1
3
2
4

3
1

1
2
3
4

1
3

3
1
2
4

The output that I am receiving is completely random on the same instance of time.我收到的输出在同一时间实例上是完全随机的。 But I want to order output for the same instance of time in the following way mentioned below:但我想以下面提到的以下方式订购同一时间实例的输出:

1
3

1
2
3
4

1
3

1
2
3
4

Is this possible to achieve the above scenario using the same Cron Expression?这是否可以使用相同的 Cron 表达式实现上述场景?

You would have to add smaller unit of time:您将不得不添加较小的时间单位:

@Scheduled(cron = "0 */1 * * * ?")
public void method1()  {
    System.out.println("1");
}

@Scheduled(cron = "1 */2 * * * ?")
public void method2(){
    System.out.println("2");
}

@Scheduled(cron = "2 */1 * * * ?")
public void method3()  {
    System.out.println("3");
}

@Scheduled(cron = "3 */2 * * * ?")
public void method4()  {
    System.out.println("4");
}

Edit: other implementation:编辑:其他实现:

public void method1()  {
    System.out.println("1");
}

public void method2(){
    System.out.println("2");
}

public void method3()  {
    System.out.println("3");
}

public void method4()  {
    System.out.println("4");
}

@Scheduled(cron = "0 */2 * * * *")
public void even() {
    method1();
    method2();
    method3();
    method4();
}

@Scheduled(cron = "0 1/2 * * * *")
public void odd() {
    method1();
    method3();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM