Spring Boot timed Task single-threaded and multi-threaded _springboot timed tasks

Source: Internet
Author: User
Tags dateformat

Scheduled Tasks for Spring Boot:

First: Configure the parameters in the. Properties file:

Code:

Package com.accord.task;

Import Java.text.SimpleDateFormat;
Import java.util.Date;

Import org.springframework.scheduling.annotation.Scheduled;
Import org.springframework.stereotype.Component;

/**
 * Load task information from configuration file
 * @author Wang Juyin
 * March 1, 2018 * *
@Component public
class Scheduledtask {

  private static final SimpleDateFormat DateFormat = new SimpleDateFormat ("HH:mm:ss");

  @Scheduled (fixeddelaystring = "${jobs.fixeddelay}")
  @Scheduled (fixeddelaystring = "??") Public
  Void GetTask1 () {
    System.out.println ("Task 1, Load task information from configuration file, current time:" + Dateformat.format (new Date ());
  }

  @Scheduled (cron = "${jobs.cron}") Public
  void GetTask2 () {
    System.out.println ("Task 2, load task information from configuration file, current time:" + Dateformat.format (New Date ());
  }
Application.properties file:

jobs.fixeddelay=5000 JOBS.CRON=0/5 * * * * *  ?

In Springbootcron2application.java:

Package Com.accord;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling Public
class Springbootcron2application {public
	static void Main (string[] args) {
		springapplication.run (springbootcron2application.class, args);
	}
}

Note: @EnableScheduling this must be added, otherwise, the task will not start regularly. Description of the parameters in the @Scheduled:

@Scheduled (fixedrate=2000): 2 seconds after the last start of the execution time;

@Scheduled (fixeddelay=2000): 2 seconds after the last execution point;

Scheduled (initialdelay=1000, fixeddelay=2000): The first delay is 1 seconds, and then executed 2 seconds after the last execution time; @Scheduled (cron= "* * * * *

?") : Executed by cron rule.
On-line cron Expression Builder: http://cron.qqe2.com/


Second timing tasks: single-threaded and multi-threaded

1. Create timed tasks:

Package com.accord.task;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.scheduling.annotation.Scheduled;

Import org.springframework.stereotype.Component; /** * Build Execute Timed Task * @author Wang Juyin * March 1, 2018 * TODO/@Component public class ScheduledTask2 {private Logger Logge

    R = Loggerfactory.getlogger (Scheduledtask2.class);
    private int fixeddelaycount = 1;
    private int fixedratecount = 1;
    private int initialdelaycount = 1;

    private int croncount = 1; @Scheduled (Fixeddelay = 5000)//fixeddelay = 5000 indicates that the Spring scheduling calls the method public void Testfi again after the current method has finished executing 5000ms
    Xdelay () {Logger.info ("===fixeddelay: {} execution Method", fixeddelaycount++); @Scheduled (fixedrate = 5000)//fixedrate = 5000 indicates that the Spring scheduling calls the method public void T again after the current method starts executing 5000ms
    Estfixedrate () {Logger.info ("===fixedrate: {} execution Method", fixedratecount++); } @Scheduled (InitialDelay = 1000, fixedrate = 5000)//initialdelay = 1000 indicates delay 1000ms perform the first task public void Testinitialdelay () {Logger.info ("===initialdelay: {} execution method", Initialdela
    ycount++);  @Scheduled (cron = "0 0/1 * * * *") Cron accepts a cron expression that determines the timing rule public void Testcron () {Logger.info ("===initialdelay: {} execution Method", croncount++) according to a cron expression
    ;
 }

}

Use @Scheduled to create a timed task this annotation is used to mark a timed task method.
By looking at @Scheduled source can see that it supports a variety of parameters:
(1) Cron:cron expression that specifies that the task is executed at a specific time;
(2) Fixeddelay: Indicates how often after the last task execution is completed, the parameter type is long and the unit MS;
(3) Fixeddelaystring: Just like the meaning of Fixeddelay, only the parameter type becomes string;
(4) Fixedrate: To perform the task according to a certain frequency, the parameter type is long, the unit MS;
(5) Fixedratestring: As with the meaning of fixedrate, only the parameter type is changed to string;
(6) InitialDelay: Indicates how long the delay and the first time to perform the task, the parameter type is long, unit MS;
(7) Initialdelaystring: As with the meaning of InitialDelay, only the parameter type is changed to string;
(8) Zone: The time zone, which defaults to the current time zone, is generally not used.
2, start the timing task:

Package Com.accord;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling Public
class Springbootcron2application {public
	static void Main (string[] args) {
		springapplication.run (springbootcron2application.class, args);
	}
}

Note: The @EnableScheduling annotation here, its function is to find the annotation @Scheduled task and run by the background. A timed task cannot be performed without it.
Quote Official Document Original:
@EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.

3. Execution result (single thread)

A simple timing task model is completed, following the execution of Springboot observation results:


From the results of the console input, we can see that all the timing tasks are in the same thread pool with the same threads to deal with, then how do we deal with the timing of the task, please continue to look down.

4. Multi-thread Processing timing task:

See the results of the console output, all the timing tasks are handled through a thread, I estimate that the timing of the task configuration set a singlethreadscheduledexecutor, so I looked at the source code, Start all the way down the Scheduledannotationbeanpostprocessor class. Sure enough, in the Scheduledtaskregistrar (scheduled task registration Class) in the scheduletasks in another such a judgment:

if (This.taskscheduler = = null) {
	this.localexecutor = Executors.newsinglethreadscheduledexecutor ();
	This.taskscheduler = new Concurrenttaskscheduler (this.localexecutor);
}
This means that if the TaskScheduler is empty, then a single-threaded thread pool is given to the timed task, and there is a way to set the TaskScheduler in this class:

public void Setscheduler (Object scheduler) {
	assert.notnull (Scheduler, "Scheduler Object must is not null");
	if (scheduler instanceof TaskScheduler) {
		This.taskscheduler = (taskscheduler) scheduler;
	}
	else if (scheduler instanceof Scheduledexecutorservice) {
		This.taskscheduler = new Concurrenttaskscheduler (( Scheduledexecutorservice) scheduler));
	}
	else {
		throw new IllegalArgumentException ("Unsupported Scheduler Type:" + scheduler.getclass ());
	}
This problem is very simple, we only need to call this method explicitly set a scheduledexecutorservice can achieve the effect of concurrency. All we have to do is implement the Schedulingconfigurer interface, rewrite the Configuretasks method on the OK;

Package com.accord.task;

Import org.springframework.context.annotation.Configuration;
Import Org.springframework.scheduling.annotation.SchedulingConfigurer;
Import Org.springframework.scheduling.config.ScheduledTaskRegistrar;

Import java.util.concurrent.Executors;

/**
 * Multithreading perform timed tasks
 * @author Wang Juyin
 * March 1, 2018 * *
@Configuration
//All scheduled tasks are placed in a thread pool, Timed tasks are started with different threads. The public
class Scheduleconfig implements Schedulingconfigurer {@Override the public
    void Configuretasks ( Scheduledtaskregistrar taskregistrar) {
        //Set a timer task thread pool of length 10
        taskregistrar.setscheduler ( Executors.newscheduledthreadpool ());
    }
5. Execution results (concurrent)


The result of the console output shows that each timed task is handled by a different thread.

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.