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:
- Start adding classes
@EnableScheduling
enable the scheduled task, automatically scan - Traffic class annotated timer task
@Component
is to scan the container - Regular implementation of the method comment on
@Scheduled
a 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:
- Start adding classes
@EnableAsync
enable the scheduled task, automatically scan. - Asynchronous task class defined using
@Component
labeled container scanning assembly is coupled, asynchronous method@Async
. controller
Layer calls the asynchronous task methods can be.
The following code ( @Async
act 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));
}
}