简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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