How to use TaskScheduler in Spring
Xiaobian to share with you how to use TaskScheduler in Spring, I believe most people still do not know how to use it, so share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
TaskScheduler
Provide support for scheduling tasks; use @EnableScheduling to enable scheduling tasks; support @Scheduled to annotate scheduling tasks;
example
Demonstrate background intermittent execution and scheduled tasks
Configuration of scheduled tasks
@Configuration@EnableSchedulingpublic class DemoConfig {}
Plan Configuration Task Class
package com.wisely.task.scheduler;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class DemoScheduledTask { private static final SimpleDateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss"); @Scheduled (fixedRate = 5000) //executes every five seconds public void reportCurrentTime() { System.out.println ("Execute every five seconds" + dateFormat.format(new Date())); } @Scheduled(cron = "0 22 11 ? * *" ) //public void fixTimeExecution(){ System.out.println(" At specified time " + dateFormat.format(new Date())+" Execute ") every day at 11:22 AM; }}
test
package com.wisely.task.scheduler;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main { @SuppressWarnings({ "unused", "resource" }) public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.wisely.task.scheduler"); }}
output result
Every five seconds 11:21:42 Every five seconds 11:21:47 Every five seconds 11:21:52 Every five seconds 11:21:57 At the specified time 11:22:00 Every five seconds 11:22:02
The above is "How to use TaskScheduler in Spring" all the contents of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!