When writing Spring Boot applications, you will encounter such scenarios, such as: you need to send some text messages, emails and other operations regularly, and you may also check and monitor some flags, parameters, etc.
Create a timed task
It is very simple to write a timed task in Spring Boot. The following examples are used to introduce how to create a timed task in Spring Boot, so as to output the current time every 5 seconds.
Add @EnableScheduling annotation to the main class of Spring Boot to enable the configuration of timing tasks
import org.springframework.boot.SpringApplicationimport org.springframework.boot.autoconfigure.SpringBootApplicationimport org.springframework.scheduling.annotation.EnableScheduling/*** Created by http://quanke.name on 2018/1/12.*/@SpringBootApplication@EnableSchedulingclass Applicationfun main(args: Array<String>) {SpringApplication.run(Application::class.java, *args)}Create a timed task implementation class
import org.apache.commons.logging.LogFactoryimport org.springframework.scheduling.annotation.Scheduledimport org.springframework.stereotype.Componentimport java.text.SimpleDateFormatimport java.util.*/*** Created by http://quanke.name on 2018/1/12.*/@Componentclass ScheduledTasks {val log = LogFactory.getLog(ScheduledTasks::class.java)!!private val dateFormat = SimpleDateFormat("HH:mm:ss")@Scheduled(fixedRate = 1000)fun reportCurrentTime() {log.info("CurrentTime, ${dateFormat.format(Date())}")}}Run the program and you can see the following output in the console. The timing task begins to operate normally.
2018-01-21 23:09:01.112 INFO 23832 ― [ main] nqkotlin.chaper11_8_1.ApplicationKt : Started ApplicationKt in 8.024 seconds (JVM running for 8.724)
2018-01-21 23:09:02.112 INFO 23832 ― [pool-2-thread-1] nqkchaper11_8_1.task.ScheduledTasks : Current time, 23:09:02
2018-01-21 23:09:03.042 INFO 23832 ― [pool-2-thread-1] nqkchaper11_8_1.task.ScheduledTasks : Current time, 23:09:03
2018-01-21 23:09:04.042 INFO 23832 ― [pool-2-thread-1] nqkchaper11_8_1.task.ScheduledTasks : Current time, 23:09:04
2018-01-21 23:09:05.042 INFO 23832 ― [pool-2-thread-1] nqkchaper11_8_1.task.ScheduledTasks : Current time, 23:09:05
@ScheduledDetails
In the above introductory example, the @Scheduled(fixedRate = 1000) annotation is used to define the tasks executed every 1 second. The use of @Scheduled can be summarized in the following ways:
@Scheduled annotation is single-threaded. If multiple threads are required, please add @Async
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.