{"id":7539,"date":"2021-09-06T04:30:13","date_gmt":"2021-09-06T08:30:13","guid":{"rendered":"https:\/\/springframework.guru\/?p=7539"},"modified":"2022-02-04T12:28:03","modified_gmt":"2022-02-04T17:28:03","slug":"scheduling-in-spring-boot","status":"publish","type":"post","link":"https:\/\/springframework.guru\/scheduling-in-spring-boot\/","title":{"rendered":"Scheduling in Spring Boot"},"content":{"rendered":"<p>We use scheduling to schedule jobs in a Spring Boot application. For instance, you can implement scheduling to perform some task at a specific time, or repeat after a fixed interval.<\/p>\n<p>In this post, you\u2019ll learn how to use the Spring <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">@Scheduled<\/code> annotation to configure and schedule tasks.<\/p>\n<h2>Spring Boot @Scheduled Annotation Example<\/h2>\n<p>Let\u2019s say you want to run a job every 5 seconds. You can achieve it by following the below steps:<\/p>\n<p><strong>Step 1: @EnableScheduling annotation<\/strong><\/p>\n<p>Add the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">@EnableScheduling<\/code> annotation to the main class.<\/p>\n<p>It is a Spring Context module annotation that internally imports <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">SchedulingConfiguration<\/code>.<\/p>\n<p>The code for the Main class is this.<\/p>\n<p><strong>SchedulingDemoApplication.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@EnableScheduling\r\n@SpringBootApplication\r\npublic class SchedulingDemoApplication {\r\npublic static void main(String[] args) {\r\n     SpringApplication.run(SchedulingDemoApplication.class, args);\r\n  }\r\n}\r\n<\/pre>\n<p><strong>Step 2: @Scheduled annotation<\/strong><\/p>\n<p>Add Spring Boot <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">@Scheduled<\/code> annotation on the methods that you want to schedule.<\/p>\n<p>You need to ensure two conditions while annotating a method with <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">@Scheduled<\/code>:<\/p>\n<ul>\n<li>The method should typically have a void return type (if not, the returned value will be ignored).<\/li>\n<li>The method should not expect any parameters.<\/li>\n<\/ul>\n<p>Let us look into some scheduling use cases.<\/p>\n<h3>Case 1: Schedule a Task at a Fixed Delay<\/h3>\n<p>In this case, the duration between the end of the last execution and the start of the next execution is fixed. The task always waits until the previous one is finished.<\/p>\n<p>The code for the above case is this.<\/p>\n<p><strong>SchedulingDemoApplication.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Scheduled(fixedDelay = 10000)\r\npublic void run() {\r\n  System.out.println(\"Current time is :: \" + Calendar.getInstance().getTime());\r\n}\r\n<\/pre>\n<p>Use this option when the previous execution has to be completed before running again.<\/p>\n<p>The output for the preceding code is this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_delay.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-7595\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_delay-1024x385.jpg\" alt=\"\" width=\"1024\" height=\"385\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_delay-1024x385.jpg 1024w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_delay-300x113.jpg 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_delay-768x289.jpg 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_delay-848x319.jpg 848w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_delay-410x154.jpg 410w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_delay.jpg 1287w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/p>\n<h3>Case 2: Schedule a Task at a Fixed Rate<\/h3>\n<p>In this use case, each execution of the task is independent.<\/p>\n<p>This is the code for the second case.<\/p>\n<p><strong>SchedulingDemoApplication.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Scheduled(initialDelay = 1000, fixedRate = 10000)\r\npublic void run() {\r\n  System.out.println(\"Current time is :: \" + Calendar.getInstance().getTime());\r\n}\r\n<\/pre>\n<p>Here, the scheduled tasks don&#8217;t run in parallel by default. So even if we used <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">fixedRate<\/code>, the next task won&#8217;t be invoked until the previous one is done.<\/p>\n<p>This is the output for the preceding code.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_rate.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-7596\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_rate-1024x265.jpg\" alt=\"\" width=\"1024\" height=\"265\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_rate-1024x265.jpg 1024w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_rate-300x78.jpg 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_rate-768x199.jpg 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_rate-848x220.jpg 848w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_rate-410x106.jpg 410w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/09\/fixed_rate.jpg 1304w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/p>\n<p><strong>When to Use Which ?<\/strong><\/p>\n<p>We can run a scheduled task using Spring&#8217;s <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">@Scheduled<\/code> annotation. However, based on the properties <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">fixedDelay<\/code> and <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">fixedRate<\/code>, the nature of execution changes.<\/p>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">fixedDelay<\/code> property ensures that there is a delay of n millisecond between the finish time of an execution of a task and the start time of the next execution of the task. For dependent jobs, it is quite helpful.<\/p>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">fixedRate<\/code> property runs the scheduled task at every n millisecond. It doesn&#8217;t check for any previous executions of the task. This is useful when all executions of the task are independent.<\/p>\n<h3>Case 3: Schedule a Task using Cron Expressions<\/h3>\n<p>A cron expression is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule. These fields, separated by white space, can contain any of the allowed values with various combinations of the allowed characters for that field.<\/p>\n<p>Sometimes delays and rates are not enough, and we need the flexibility of a cron expression to control the schedule of our tasks.<\/p>\n<p>Let us take an example of scheduling a task that is to be executed at 10 AM on the 10th day of every month.<\/p>\n<p>This is the code for the preceding example.<\/p>\n<p><strong>SchedulingDemoApplication.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Scheduled(cron = \"0 10 10 10 * ?\")\r\n    public void scheduleTask() {\r\n      System.out.println(\"Current time is :: \" + Calendar.getInstance().getTime());\r\n}\r\n<\/pre>\n<p>With this configuration, Spring will schedule the annotated method to run at 10 AM on the 10th day of every month.<\/p>\n<p>You can find the source code of this post here on <a href=\"https:\/\/github.com\/spring-framework-guru\/sfg-blog-posts\/tree\/master\/scheduling-demo\" target=\"_blank\" rel=\"noopener\">Github<\/a>.<\/p>\n<p>For in-depth knowledge on scheduling jobs in Spring Boot Microservices application, you can check my Udemy Best Seller Course <a href=\"https:\/\/www.udemy.com\/course\/spring-boot-microservices-with-spring-cloud-beginner-to-guru\/\" target=\"_blank\" rel=\"noopener\">Spring Boot Microservices with Spring Cloud Beginner to Guru<\/a><\/p>\n<p><a href=\"https:\/\/www.udemy.com\/course\/spring-boot-microservices-with-spring-cloud-beginner-to-guru\/\" target=\"_blank\" rel=\"noopener\"><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7006\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/03\/microservices.jpg\" alt=\"\" width=\"800\" height=\"315\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>We use scheduling to schedule jobs in a Spring Boot application. For instance, you can implement scheduling to perform some task at a specific time, or repeat after a fixed interval. In this post, you\u2019ll learn how to use the Spring @Scheduled annotation to configure and schedule tasks. Spring Boot @Scheduled Annotation Example Let\u2019s say [&hellip;]<a href=\"https:\/\/springframework.guru\/scheduling-in-spring-boot\/\" class=\"df-link-excerpt\">Continue reading<\/a><\/p>\n","protected":false},"author":111,"featured_media":4589,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[21,104],"tags":[373,29],"class_list":["post-7539","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-spring","category-spring-boot","tag-scheduling","tag-spring-boot"],"jetpack_publicize_connections":[],"aioseo_notices":[],"modified_by":"jt","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/springframework.guru\/wp-content\/uploads\/2015\/03\/Banner560x292_05web.jpg","jetpack_shortlink":"https:\/\/wp.me\/p5BZrZ-1XB","_links":{"self":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/7539"}],"collection":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/users\/111"}],"replies":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/comments?post=7539"}],"version-history":[{"count":13,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/7539\/revisions"}],"predecessor-version":[{"id":7764,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/7539\/revisions\/7764"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media\/4589"}],"wp:attachment":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media?parent=7539"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/categories?post=7539"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/tags?post=7539"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}