Melvin
Melvin

Reputation: 31

Spring scheduling for multiple different times

I'm currently doing a project to auto scraping web content when user onclick, but I got a problem is I need to run those method in different time different seconds. I have refer to @Schedule and TimerTask, but those only will work on fixed time. Is there any solution for my case?

Code example:

public void run(String selectedWeb) {
   if(selectedWeb.equals("First Web")) {
      scrapeFirstWeb(); //Need this method auto execute on 8, 30, 42 seconds every minute
   }else if(selectedWeb.equals("Second Web")) {
      scrapeSecondWeb(); //Need this method auto execute on 10am, 1pm, 11pm every day
   }    
}

PS: I have used @Scheduled annotation with cron before, but there is a problem which is this annotation will auto run all the method include those I didn't select to run. Because I may have situation to only scrape First Web or Second Web instead of both, but then the annotation will ignore which web you have select, when time is up it will excecute also. So that is my problem.

If anyone know is there any way I can make @Schedule annotation run for the method I select only can do comment let me know, thanks in advance!

Upvotes: 1

Views: 3599

Answers (2)

Melvin
Melvin

Reputation: 31

Finally I have found a way to solve this problem, and it can use back @Schedule annotation also.

//Set @Scheduled annotation to false to avoid it auto execute when compile
@Value("${jobs.enabled:false}")
private boolean isEnabled;

public void run(String selectedWeb) {
   if(selectedWeb.equals("First Web")) {
      //Set it back to true when it has been selected
      isEnabled = true
      scrapeFirstWeb();
   }else if(selectedWeb.equals("Second Web")) {
      isEnabled = true
      scrapeSecondWeb();
   }    
}

@Scheduled(cron = "8,30,42 * * * * *")
    public void scrapeFirstWeb(){
    //So when isEnabled is false, it will not doing anything until it is true
    if(isEnabled){
       //Do something
    }
}

Detailed explanation can refer to here https://www.baeldung.com/spring-scheduled-enabled-conditionally

Upvotes: 1

Tal Glik
Tal Glik

Reputation: 510

I suggest using schedule executor that you can stop whenever you want:

 ScheduledExecutorService executorService = Executors
                .newSingleThreadScheduledExecutor();
        ScheduledFuture<?> in_method1 = executorService.scheduleAtFixedRate(() -> System.out.println("In method1"), 5, 3, TimeUnit.SECONDS);

        Thread.sleep(10000);
        in_method1.cancel(false);

Upvotes: 0

Related Questions