Skip to main content

Spring Boot-Schedule a task with SpringBoot-Download Source Code

In this article, You’ll learn how to schedule tasks in Spring Boot using @Scheduled annotation.To schedule job in spring boot application to run periodically, spring boot provides @EnableScheduling and @Scheduled annotations.

Add @EnableScheduling to Spring Boot Application class

Add @EnableScheduling annotation to your spring boot application class. @EnableScheduling is a Spring Context module annotation. It internally imports the SchedulingConfiguration via the @Import(SchedulingConfiguration.class) instruction

@SpringBootApplication
@EnableScheduling
public class KnowledgefactoryScheduler {

public static void main(String[] args) {
SpringApplication.run(KnowledgefactoryScheduler.class, args);
}
}


1. Scheduling a Task with Fixed Rate

You can schedule a method to be executed at a fixed interval by using fixedRate parameter in the @Scheduled annotation. In the following example, The annotated method will be executed every 3 seconds.
     
// Scheduling a Task with Fixed Rate
@Scheduled(fixedRate = 3000)
public void scheduleTaskWithFixedRate() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("Scheduled task with Fixed Rate:" +                                                               sdf.format(cal.getTime()));
}

Output:

Scheduled task with Fixed Rate:22:09:42
Scheduled task with Fixed Rate:22:09:45
Scheduled task with Fixed Rate:22:09:48
Scheduled task with Fixed Rate:22:09:51


2. Scheduling a Task with Fixed Delay

You can execute a task with a fixed delay between the completion of the last invocation and the start of the next, using fixedDelay parameter.

The fixedDelay parameter counts the delay after the completion of the last invocation.

  // Scheduling a Task with Fixed Delay
@Scheduled(fixedDelay = 3000)
public void scheduleTaskWithFixedDelay() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new                                                                                     SimpleDateFormat("HH:mm:ss");
System.out.println("Scheduled task With with Fixed Delay:" +                                         sdf.format(cal.getTime()));
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
}

Since the task itself takes 5 seconds to complete and we have specified a delay of 3 seconds between the completion of the last invocation and the start of the next, there will be a delay of 8 seconds between each invocation -

Output:

Scheduled task With with Fixed Delay:22:16:54
Scheduled task With with Fixed Delay:22:17:02
Scheduled task With with Fixed Delay:22:17:10


3. Scheduling a Task With Fixed Rate and Initial Delay

You can use initialDelay parameter with fixedRate and fixedDelay to delay the first execution of the task with the specified number of milliseconds.
In the following example, the first execution of the task will be delayed by 5 seconds and then it will be executed normally at a fixed interval of 3 seconds -

  // Scheduling a Task With Fixed Rate and Initial Delay
@Scheduled(fixedRate = 3000, initialDelay = 6000)
public void scheduleTaskWithInitialDelay() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new                                                                               SimpleDateFormat("HH:mm:ss");
System.out.println("Scheduled task With Fixed Rate and Initial Delay:" + sdf.format(cal.getTime()));
}


4. Scheduling a Task using Cron Expression

If the above simple parameters can not fulfill your needs, then you can use cron expressions to schedule the execution of your tasks.
Let us see some examples of cron expression by using the fields and specials characters combinations:
Every Christmas Day at midnight

  // Scheduling a Task using Cron Expression:every Christmas Day at                        midnight
@Scheduled(cron = "0 0 0 25 12 ?")
public void scheduleTaskWithCronExpression() {
System.out.println("Scheduled Task using Cron Expression:every                          Christmas Day at midnight");
}




Download Source Code 

$gitclone 
https://github.com/knowledgefactory4u/KnowledgeFactory

Comments

Popular posts from this blog

Spring boot video streaming example-HTML5

This article shows you how to stream MP4 video in Spring Boot web application 
User Interface

Project Structure

Home Controller
@Controller
public class HomeController {
 @Autowired
 private MyResourceHttpRequestHandler handler;
 private final static File MP4_FILE = new File("D:\\videofiles\\video1.mp4");
 // supports byte-range requests
 @GetMapping("/index")
 public String home() {
  return "index";
 }
 // supports byte-range requests
 @GetMapping("/byterange")
 public void byterange( HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setAttribute(MyResourceHttpRequestHandler.ATTR_FILE, MP4_FILE);
  handler.handleRequest(request, response);
 }}
Spring Boot 
@SpringBootApplication
@ComponentScan({ "com" })
public class KnowledgefactorydemoApplication {
 public static void main(String[] args) {
  SpringApplication.run(KnowledgefactorydemoApplication.class, args);
 }}
MyResource HttpRequestHandler
@Componen…

DataTable-Pagination example with Spring boot,jQuery and ajax free download

This article shows you DataTable-Pagination example with Spring boot, jQuery and ajax. 

Following technologies stack being used:
Spring Boot 2.1.1.RELEASESpring 5.1.3.RELEASE Maven 3DatatablejQueryFree Markerjavascriptajax Project Structure
View(index.ftl) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Knf|Pagination-Datatables</title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../../css/jquery.dataTables.min.css"> <body>  <section class="content">   <div class="container-fluid">    <table id="example" class="display" style="width: 100%">     <thead>      <tr>       <th>First name</th>       <th>La…

9 Best Job Posting Sites for Employee 2020-2022

One of the most common ways today’s job seekers uncover employment opportunities are by using online sources. There are hundreds of job boards, both generic and niche, as well as aggregators, social media channels, networking groups, and staffing company websites to choose from. The good news is they provide plenty of listings. The bad news is you can be easily overwhelmed by so many options. Here, knowledge factory offers 9 of what is generally considered the best job search websites around. There are many others, of course, but this list of best job search websites should give you a good starting point for your next job hunt: 1. LinkedIn
This top networking site allows you to find jobs through your extended network. User profiles serve as resumes. You can easily share career-related content and solicit or supply recommendations. Additionally, you can join groups, participate in conversations, and follow companies you find interesting and relevant to your job search. Premium pai…