Scheduler is a mechanism that supports executing of tasks periodically or at certain periods of time, without need to run tasks manually. For example, sometimes in an application we need to run some analysis every one hour, or we need to send an email notification every Monday at 08:00 AM, but we don’t want to be responsible for running these tasks each time. Using a scheduler would help implement these kinds of requirements.

In this Tech Bite will be illustrated Java Spring Boot support for scheduling tasks that is simple to implement even in the smallest applications.

1. Enable support for scheduling

Scheduling support will be simply enabled by adding annotation @EnableScheduling to the main class:

@SpringBootApplication
@EnableScheduling
public class SchedulerApplication {

    public static void main(String[] args) {

        SpringApplication.run(SchedulerApplication.class, args);

    }
}

2. Add scheduler service

Scheduler service class will hold scheduled methods. These methods will perform tasks that need to be executed in a certain period of time or periodically and have to be annotated with @Scheduled

In this case, method printCurrentTime() will print current time in the console each time that task is executed.

@Component
public class SchedulerService {

    @Scheduled
    public void printCurrentTime() {
        LocalTime currentTime = LocalDateTime.now().toLocalTime();

        System.out.println("Current time is: " + currentTime);
    }
}

3. Schedule task

Final step is to properly set attributes of @Scheduledannotation, depending on when we want a task to run. If we want task to run every second we set:

@Scheduled(fixedRate = 1000)

This annotation also supports cron expressions, so if we want to schedule task every Monday at 08:00 AM we set:

@Scheduled(cron = “0 0 8 ? * MON *”)

More about each attribute can be found in official documentation.

4. Read attributes from configuration file (optional)

When we want to change configuration for a scheduler, usually we don’t want to redeploy the entire application. So, good practice for values that are configuring schedulers would be to put them in the application properties file. In that case we can change configuration easily.

@Scheduled(fixedRateString = "${project.scheduler.fixedRate}")

or

@Scheduled(cron = "${project.scheduler.cronExpression}")

Schedulers in Java Tech Bite was brought to you by Lejla Kasum, Software Engineer at Atlantbh.

Tech Bites are tips, tricks, snippets or explanations about various programming technologies and paradigms, which can help engineers with their everyday job.

oban
Software DevelopmentTech Bites
February 23, 2024

Background Jobs in Elixir – Oban

When and why do we need background jobs? Nowadays, background job processing is indispensable in the world of web development. The need for background jobs stems from the fact that synchronous execution of time-consuming and resource-intensive tasks would heavily impact an application's  performance and user experience.  Even though Elixir is…
selenium
QA/Test AutomationTech Bites
December 22, 2023

Selenium Grid 4 with Docker

Introduction When talking about automation testing, one of the first things that comes to mind is Selenium. Selenium is a free, open-source automated testing framework used to validate web applications across different browsers and platforms. It is not just a single tool but a suite of software. Every component of…
redis
Software DevelopmentTech Bites
December 22, 2023

In-memory Caching using Redis

The importance of computer memory utilization The CPU and memory are the main components of any computer system. Computer memory stores data and program instructions, temporarily or permanently, that the CPU processes. In CPU-intensive applications with large amounts of data being processed, memory usually becomes the bottleneck, resulting in a…

Leave a Reply