Okeme Christian
Okeme Christian

Reputation: 312

Using @Schedule in spring

Hello i working on a cron job and would like to schedule the task to run once every two weeks on a Monday morning using @schedule in spring can anyone help me out here?

Upvotes: 2

Views: 475

Answers (4)

Haoliang
Haoliang

Reputation: 1264

Regarding the cron expression for every two weeks, here're some discussion.

It seems not very convenient to use cron expression to set two weeks schedule. Instead, you can use cron expression to set weekly tasks, and use a boolean variable to flip the boolean value:

boolean flag;

// run the method at 8:00 AM every Monday
@Scheduled(cron="0 0 8 * * MON")
public void schedulingTask() {
    // run the actual task only if flag is true
    if (flag) {
        // handle the biweekly task 
    }
    // flip the flag
    flag = !flag;
}

Upvotes: 0

Roon
Roon

Reputation: 81

If you use not springboot but spring framework, you can configure scheduling job like below.

@EnableScheduling
@Configuration
public class SchedulingConfig {
 // ...
}

And use like this.

private static final int TEN_MINUTES = 60 * 10 * 1000;

@Scheduled(fixedRate = TEN_MINUTES)
public void doSomething() {
  // ...
}

Upvotes: 0

jstuartmilne
jstuartmilne

Reputation: 4508

As the other answer mentioned you just have to add the @Scheduled annotation. however if using spring boot dont forget to add this anotation @EnableScheduling in the main class of your app

@EnableScheduling
@EnableAutoConfiguration
public class MyApplication {

Hope it helps

Upvotes: 1

Michael W
Michael W

Reputation: 3555

You should check out the getting started examples in the spring.io website:

Scheduling Tasks

For your use case you'll be using the scheduled annotation with a cron expression:

@Scheduled(cron=". . .")

This uses the CronSequenceGenerator.

Upvotes: 1

Related Questions