Scheduling

Scheduling is a feature that allows us to automatically trigger or execute a specific task or activity at a defined interval or specific time without manual intervention.

Sending emails, processing orders are all examples of scheduled task.

Implementation

To enable scheduling in spring application, add class level @EnableScheduling annotation parallel to @SpringBootApplication annotation. This will allow our application to schedule task.

Create a sample component class having @Component class level annotation. Also, create a custom method and annotate same with @Scheduled annotation to schedule a task.

OUTPUT:

fixedRate attribute will allow us to print or run printMessage() method in every 5 seconds.

Schedule annotation mainly have three attributes:

Fixed Rate (fixedRate = 5000)

Task / Method will re-run in every 5 seconds irrespective of earlier task completion. It may be an issue if earlier task took more than 5 seconds.

Fixed Delay (fixedDelay = 5000)

The task will re-run after a delay of 5 seconds from the completion of the previous task execution.

    Initial Delay (initialDelay = 5000)

    Task will start with the initial delay of 5 seconds.

    In Above code, task will start with 10 seconds delay and will have 5 seconds of normal delay after every task.

    Schedule Task through Cron Expression

    Task can be schedule using Cron expression as it allow us to run the task periodically at specific day, time and date.

    A cron expression is a string used to define scheduling patterns in Spring, allowing you to run tasks at specific times or intervals.

    Cron Syntax = * * * * * * (six stars)

    Example:

    @Scheduled(cron = “0 0 9 * * ?”) -> Running task every day at 9:00 AM

    Below scheduler will print “Hello !!!” every day at 9 am.

    Important Note:

    It is not considered a best practice to hardcode scheduler timings or cron expressions directly in the Java code.

    Instead, it’s recommended to externalize these values by defining them in the application.properties (or application.yml) file, or storing them in a database.

    This approach allows for easier maintenance and flexibility, enabling us to change the schedule time and expression without modifying or redeploying the code.

      Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 12 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

      0