How I used Cron Jobs to perform a task in Springboot
Welcome back, guys! Today, I will like to share how I implemented a little with Cron Jobs in spring-boot with the @Scheduler annotation.
What is Cron Jobs?
Cron Jobs is a program that schedules jobs depending on some specified time.
How I created my own Scheduler.
Step 1: After I created my spring-boot application. Literally, I should not have too many dependencies because I am not building a full spring-boot application. This is what my pom.xml file looks like:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
Step 2: In my main class, I annotated it with @EnableScheduling. So, basically, that annotation will be used to enable the scheduler for your application. This should always be in your application entry point in my case I used the main class.
Step 3: I created a service package where I created a class named Scheduler.
The @Component annotation simply means it will allow Spring-boot to automatically detect our custom beans.
The @Slf4j Causes Lombok to generate a logger field (I basically use the annotation for debugging my codes).
Lastly, we have the @Scheduled annotation with the argument “fixedDelay”. Basically, spring boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation and the fixedDelay arguments help spring-boot schedule each time every task should be performed. In my case I want every task to be performed every 30s.
Step 4: Now, I will run my application and should expect every task to perform every 30s.
Now, we can see how our scheduler performs tasks every 30s. We can implement it in other big projects, like a fintech application, a social application and many more.
I will off help in case you need me to collaborate on a project with you.
You can check my GitHub link here
You can check my LinkedIn profile here
You can check my portfolio here
Thank you for reading. zip it now!