H.Ç.T
H.Ç.T

Reputation: 3579

How to run @Scheduled job at exact time for once in Spring?

Let's say I want to run a job for once in 06.02.2020 13:50. How can I do that?

By using expression below I can achive that it will run at 13:50 today. But it will be run next year too. But I want this to run just once.

@Scheduled(cron = "0 50 13 6 2 ?")

Upvotes: 0

Views: 1818

Answers (2)

Silverfang
Silverfang

Reputation: 359

This is a workaround to your solution. Just use the scheduled annotation as it is but Use Date with it. That is

    String targetDate="2020-02-06 13:50:00";
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(targetDate);
    if(new Date().getTime()==date.getTime())
    {
      then put your logic here.
   }

edit -> Just checking the year would be enough right. So you can do this.

@Scheduled(cron = "0 50 13 6 2 ?")
public void doTheJobForOnceInSpecificTime() {
    if (Year.now().getValue() == 2020) {
        //your logic
    }
}

Upvotes: 2

Ijhar Ansari
Ijhar Ansari

Reputation: 310

if you add the year, at last, it will execute only once.

@Scheduled(cron = "0 50 13 6 2 ? 2020")

Upvotes: -1

Related Questions