Springboot integration tasks and the timing of asynchronous task processing

First, the regular tasks

1. Timing common task framework

Explanation
Java comes with the regular tasks Java comes java.util.Timer
the Timer : Configuration is too much trouble, time delay problem
TimerTask : not recommended
Quartz Configuration with respect to the Java comes easier
SpringBoot comes with regular tasks Direct can enable the scheduled tasks comment

2. Use the built-in timer task Springboot

step:

  1. Start adding classes @EnableSchedulingenable the scheduled task, automatically scan
  2. Traffic class annotated timer task @Componentis to scan the container
  3. Regular implementation of the method comment on @Scheduleda regular basis

Timing task code:

@Component
public class TestTask {
    @Scheduled(fixedRateString = "2000")
    public void test2() {
        System.out.println("结束 当前时间为:" + new Date());
    }
}

Code configuration based on the timing of the task properties:

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
      /**
       * 设置多个线程去执行 
       */
      taskRegistrar.setScheduler(
              Executors.newScheduledThreadPool(5));
  }
}

3. @ Scheduled annotation Property Description

Explanation
cron Regular tasks expressions @Scheduled(cron="*/1 * * * * *")denote per second
crontab tool https://tool.lu/crontab/
fixedRate How often performed once the timing (after the last execution start time point is performed again xx seconds)
fixedDelay After the end point of the previous execution time xx seconds to perform again
fixedDelayString A string can be specified by the configuration file, in milliseconds

Second, asynchronous tasking

Corresponds to the message queue functions, application scenarios: logging, sending email, SMS, payments, orders ...

Use Springboot comes asynchronous tasks steps:

  1. Start adding classes @EnableAsyncenable the scheduled task, automatically scan.
  2. Asynchronous task class defined using @Componentlabeled container scanning assembly is coupled, asynchronous method @Async.
  3. controllerLayer calls the asynchronous task methods can be.

The following code ( @Asyncact on the class or method):

@Async
public class AsyncTask {
    public void task1() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(1000L);
        long end = System.currentTimeMillis();
        System.out.println("任务1耗时="+(end-begin));
    }
}
发布了81 篇原创文章 · 获赞 124 · 访问量 38万+

Guess you like

Origin blog.csdn.net/qq_38697437/article/details/104545576