简体   繁体   中英

Configure Spring task scheduler to run at a fixeDelay or run at once based on a boolean

I have a code which runs at a regular interval. Below is code for that

@EnableScheduling
@Component
public class Cer {

    @Autowired
    private A a;

    @Autowired
    private CacheManager cacheManager;

    @Scheduled(fixedDelayString = "${xvc}")
    public void getData() {
        getCat();
        getB();
        return;
    }
}

I want to change @Scheduled(fixedDelayString = "${xvc}") this based on a boolean say runOnce if runOnce is true @scheduled should run once only say on code startup. Any advice how to achieve this. Thanks in advance.

I would place the functionality that you want to schedule in a component:

@Component
public class ServiceToSchedule {

    public void methodThatWillBeScheduled() {
        // whatever
        return;
    }
}

And have two additional components that will be instantiated depending on a Profile . One of them schedules the task, and the other one just executes it once.

@Profile("!scheduled")
@Component
public class OnceExecutor {

    @Autowired
    private ServiceToSchedule service;

    @PostConstruct
    public void executeOnce() {
        // will just be execute once
        service.methodThatWillBeScheduled();
    }
}


@Profile("scheduled")
@Component
@EnableScheduling
public class ScheduledExecutor {

    @Autowired
    private ServiceToSchedule service;

    @Scheduled(fixedRate = whateverYouDecide)
    public void schedule() {
        // will be scheduled
        service.methodThatWillBeScheduled();
    }
}

Depending on which profile is active, your method will be executed just once ( scheduled profile is not active), or will be scheduled ( scheduled profile is active).

You set the spring profiles by (for example) starting your service with:

-Dspring.profiles.active=scheduled

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