What is Cron Job ? How to Create Cron Job in Core Java ?

The world now speaks language of automation. Anything that can save manual efforts and can be automated is trending up now a days.

Cron Job is kind of scheduled task. Say every one hour you want to generate some report say sales report regarding sales happened in last one hour. You can do it manually but can you be present all 24 hours and you need to send an email with report as well. Will you be able to do it ?

Obviously your answer will be NO. Actually a big NOOOO...

In this article I will show you how you can create Cron job which is basically scheduler using just Core Java. I am saying core java only because there are couple of third part libraries are available for the same. But that libraries we will see some other day as in this article we are just going with Core Java ONLY.

So here you need 2 classes. One that will contain your business logic to obtain sales happened in last one hour and then code to send out an email. Say that class is TaskToPerform. It should extend TimerTask abstract class and override the run method. Inside this run method you need to put your business logic because at every interval (in our example its one hour) this run method will get called. Other class is our main class where we define the interval to perform this task.

Let's see the code part. Below is our TaskToPerform class.
package com.infybuzz.cronjob;

import java.util.Date;
import java.util.TimerTask;

public class TaskToPerform extends TimerTask {

 @Override
 public void run() {
  // business logic according to your application and needs
  System.out.println(new Date());
 }

}

Here is our main class which is CronJobExample. Here Lets set interval as 1 second i.e 1000 miliseconds and lets print out date inside run() method of TaskToPerform.
package com.infybuzz.cronjob;

import java.util.Timer;

public class CronJobExample {

 public static void main(String[] args) {
  Timer timer = new Timer();
  TaskToPerform task = new TaskToPerform();
  timer.scheduleAtFixedRate(task, 0, 1000); // time in miliseconds
 }

}

Checkout Below Useful Courses :-
1) Learn RabbitMQ Messaging and its practical implementation with Java, Spring Boot and Spring MVC

2) Learn Spring Social SignIn with Twitter, LinkedIn. PayPal Payment gateway Integration in Spring MVC application, Java Messaging Service (JMS) using Spring Boot and Spring MVC, Apache Velocity to send Email

3) Java Messaging Service(JMS) With Spring MVC, Spring Boot, Apache ActiveMQ

4) Java Interview Preparation || 100+ Quality Questions Covered

0 Comments