Spring @Scheduled批注在同一时间实例中执行

问题描述 投票:0回答:1
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");
    }
}

实际输出:

1
3

1
3
2
4

3
1

1
2
3
4

1
3

3
1
2
4

我收到的输出在相同的时间实例上是完全随机的。但是我想通过下面提到的以下方式对同一时间实例的输出进行排序:

1
3

1
2
3
4

1
3

1
2
3
4

是否可以使用相同的Cron表达式实现上述方案?

java spring cron scheduled-tasks spring-scheduled
1个回答
0
投票

您将不得不增加较小的时间单位:

@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");
}
© www.soinside.com 2019 - 2024. All rights reserved.