Peter Penzov
Peter Penzov

Reputation: 1754

Execute Scheduler in a fixed hours

I want to execute this Job 2 times every day:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class AppScheduler {

    @Scheduled(fixedRate = 10000)
    public void myScheduler() {
        System.out.println("Test print");
    }

}

First time at 11:00 and second time at 14:00.

Is there a way to configure these hours?

Upvotes: 1

Views: 827

Answers (3)

xingbin
xingbin

Reputation: 28289

You can use cron expression:

@Scheduled(cron = "0 0 11,14 * * *")

Upvotes: 1

tomas
tomas

Reputation: 840

@Scheduled(cron = "0 0 11,14 * * *")

This means

At second :00, at minute :00, at 11am and 14pm, of every day

You can generate it here https://www.freeformatter.com/cron-expression-generator-quartz.html

Upvotes: 1

Peter Walser
Peter Walser

Reputation: 15706

Yes, you can use CRON expressions to schedule task executions at given days/hours:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html

In your example it would look as follows:

@Scheduled(cron="0 0 11,14 * * *")

Upvotes: 4

Related Questions