1

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.

Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109
GP007
  • 691
  • 2
  • 9
  • 24
  • What is your version of Spring ? Possible duplicate of http://stackoverflow.com/questions/2598712/how-to-parameterize-scheduledfixeddelay-with-spring-3-0-expression-language. – Gaël J Oct 12 '15 at 07:42
  • using spring boot version 1.2.3.RELEASE – GP007 Oct 12 '15 at 07:50

1 Answers1

0

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
Ruben
  • 3,986
  • 1
  • 21
  • 34