0

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 ?")
H.Ç.T
  • 3,335
  • 1
  • 18
  • 37

2 Answers2

2

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
    }
}
H.Ç.T
  • 3,335
  • 1
  • 18
  • 37
Silverfang
  • 349
  • 1
  • 8
  • Thanks for the answer. But I think it is nearly impossible to get exactly same time in if statement. So comparing just the year can be enough. If you agree with me you can consider to edit the answer, then I can accept it. – H.Ç.T Feb 06 '20 at 18:48
  • Yes, Comparing the years should be enough. – Silverfang Feb 07 '20 at 04:46
-1

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

@Scheduled(cron = "0 50 13 6 2 ? 2020")
Ijhar Ansari
  • 310
  • 1
  • 2
  • 9
  • No. It will raise IllegalStateException at startup. "Cron expression must consist of 6 fields (found 7 in "0 52 13 6 2 ? 2020")" – H.Ç.T Feb 06 '20 at 11:09