Search code examples
spring-bootcronschedulerspring-scheduled

Spring Scheduler wont stop after loop but run for 1 minute before stop and re trigger


@Slf4j
@Component
public class ABScheduler {

  @Autowired
  private ABService abService;

  @Scheduled(cron="* */5 * * * *")
  private void testCron(){

     String hour = "01";

     List<Object1> object1List = new ArrayList<>(abService.getListOfobject(hour));

     for(Object1 object1: object1List ){
         System.out.println("object " +object1);
     }

     log.info("Cron finish run at "+ new Timestamp(System.currentTimeMillis()) );

  }
}

I'm new to this scheduler spring and I found trouble to make it stop after the for loop. After getting list of object in object1List(ie; 3 object), it enter the loop 3 time(correct). But instead stop the cron after looping 3 times, it keep looping again for duration of 1 minute..

What I need to do to make sure the cron run every 5 minutes but stop after finish it task not keep looping the same task for 1 minute


Solution

  • You should add @EnableScheduling anotation in the project.

    Your cron runs every second. (your cron second value = *)

    If you just want to work only once in five minutes, try that: @Scheduled(cron="0 */5 * * * *")

    The cron format:

       ┌───────────── second (0-59)
       │ ┌───────────── minute (0 - 59)
       │ │ ┌───────────── hour (0 - 23)
       │ │ │ ┌───────────── day of the month (1 - 31)
       │ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
       │ │ │ │ │ ┌───────────── day of the week (0 - 7)
       │ │ │ │ │ │          (0 or 7 is Sunday, or MON-SUN)
       │ │ │ │ │ │
       * * * * * *
    

    Resource: Spring Framework CronExpression