SpringBoot Schedule configuration, springbootschedule

Source: Internet
Author: User

SpringBoot Schedule configuration, springbootschedule
1. Implementation of scheduled tasks

Scheduled task implementation method:

  • Java. util. Timer class, which allows you to schedule a java. util. TimerTask task. This method allows your program to run at a certain frequency, but it cannot run at a specified time. This article will not be detailed.
  • Quartz is a powerful scheduler that allows your program to be executed at a specified time or at a certain frequency. The configuration is a little complicated and has no time to discuss.
  • SpringBoot's built-in Scheduled can be regarded as a lightweight Quartz, which is much simpler to use than Quartz. This article mainly introduces.

Scheduled task execution method:

  • Single thread (Serial)
  • Multithreading (parallel)
2. Create a scheduled task
Package com. autonavi. task. test; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springframework. scheduling. annotation. scheduled; import org. springframework. stereotype. component; import com. autonavi. task. scheduledTasks; @ Componentpublic class ScheduledTest {private static final Logger logger = LoggerFactory. getLogger (ScheduledTasks. class); @ Scheduled (cron = "0 0/2 ***? ") Public void executeFileDownLoadTask () {// The interval is 2 minutes. The execution task Thread current = Thread. currentThread (); System. out. println ("scheduled Task 1:" + current. getId (); logger.info ("ScheduledTest.exe cuteFileDownLoadTask scheduled Task 1:" + current. getId () + ", name:" + current. getName ());}}

@ Scheduled annotation is used to mark this method as a Scheduled task method. Multiple configurations are optional. Cron supports cron expressions, specifying that the task is executed at a specific time; fixedRate executes the task at a specific frequency; fixedRateString configures the execution frequency in the form of a string.

3. Start a scheduled task
@SpringBootApplication@EnableSchedulingpublic class App {    private static final Logger logger = LoggerFactory.getLogger(App.class);    public static void main(String[] args) {        SpringApplication.run(App.class, args);             logger.info("start");                            }   }

The @ EnableScheduling annotation is used to find the annotation @ Scheduled task and run it in the background.

The default execution method of Springboot itself is serial execution. That is to say, no matter how many tasks are executed, it is a thread serial execution and must be manually configured in parallel.

4. parallel Tasks

Inherit the SchedulingConfigurer class and override its method as follows:

@Configuration@EnableSchedulingpublic class ScheduleConfig implements SchedulingConfigurer {    @Override    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {        taskRegistrar.setScheduler(taskExecutor());    }    @Bean(destroyMethod="shutdown")    public Executor taskExecutor() {        return Executors.newScheduledThreadPool(100);    }}

Execute the previous Demo again and you will be glad to find that it has already been executed in parallel!

 

4. Asynchronous Parallel tasks
import org.springframework.scheduling.TaskScheduler;import org.springframework.scheduling.annotation.AsyncConfigurer;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;import org.springframework.scheduling.config.ScheduledTaskRegistrar;@Configuration@EnableScheduling@EnableAsync(mode = AdviceMode.PROXY, proxyTargetClass = false,order = Ordered.HIGHEST_PRECEDENCE)@ComponentScan(basePackages = "hello")public class RootContextConfiguration implementsAsyncConfigurer, SchedulingConfigurer {@Beanpublic ThreadPoolTaskScheduler taskScheduler(){ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();scheduler.setPoolSize(20);scheduler.setThreadNamePrefix("task-");scheduler.setAwaitTerminationSeconds(60);scheduler.setWaitForTasksToCompleteOnShutdown(true);return scheduler;}@Overridepublic Executor getAsyncExecutor(){Executor executor = this.taskScheduler();return executor;}@Overridepublic void configureTasks(ScheduledTaskRegistrar registrar){TaskScheduler scheduler = this.taskScheduler();registrar.setTaskScheduler(scheduler);}}

Add additional configurations to the main method to be started:

@SpringBootApplicationpublic class Application {    public static void main(String[] args) throws Exception {             AnnotationConfigApplicationContext rootContext =     new AnnotationConfigApplicationContext();    rootContext.register(RootContextConfiguration.class);    rootContext.refresh();    }}

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.