SpringBoot的定时任务:第一种:将参数配置到.properties文件中:代码:packagecom.accord.task;导入java.text.SimpleDateFormat;导入java.util.Date;导入org.springframework。scheduling.annotation.Scheduled;importorg.springframework.stereotype.Component;/***从配置文件加载任务信息*@author王久银*/@ComponentpublicclassScheduledTask{privatestaticfinalSimpleDateFormatdateFormat=newSimpleDateFormat("HH:mm:ss");//@Scheduled(fixedDelayString="${jobs.fixedDelay}")@Scheduled(fixedDelayString="2000")publicvoidgetTask1(){System.out.println("任务1,从配置文件加载任务信息,当前时间:"+dateFormat.format(newDate()));}@Scheduled(cron="${jobs.cron}")publicvoidgetTask2(){System.out.println("任务2,从配置文件加载任务信息,当前时间:"+dateFormat.format(newDate()));}}application.properties文件:jobs.fixedDelay=5000jobs.cron=0/5****?SpringBootCron2Application.java:packagecom.accord;我是端口org.springframework.boot.SpringApplication;导入org.springframework.boot.autoconfigure.SpringBootApplication;导入org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublicclassSpringBootCron2Application{publicstaticvoidmain(String[]arg.run(SpringBootCron2Application.class,args);}}SpringBoot的基础知识就不介绍了,推荐观看这个免费教程:https://github.com/javastacks/spring-boot-best-practice注意:@EnableScheduling这个必须是Plus,否则任务不会定时启动!@Scheduled中的参数说明:@Scheduled(fixedRate=2000):Execute在上次执行时间点2秒后再次执行;@Scheduled(fixedDelay=2000):在上次执行时间点2秒后再次执行;@Scheduled(initialDelay=1000,fixedDelay=2000):延迟1秒执行第一次,然后在上次执行时间点后2秒再次执行;@Scheduled(cron="*****?"):按照cron规则执行第二种定时任务:单线程和多线程1.创建一个定时任务:packagecom.accord.task;导入org.slf4j.Logger;导入org.slf4j.LoggerFactory;导入org.springframework.scheduling.annotation.Scheduled;导入org.springframework.stereotype.Component;/***构建并执行计划任务*@author王九银*TODO*/@ComponentpublicclassScheduledTask2{privateLoggerlogger=LoggerFactory.getLogger(ScheduledTask2.class);私有intfixedDelayCount=1;私人intfixedRateCount=1;私人intinitialDelayCount=1;私人intcronCount=1;@Scheduled(fixedDelay=5000)//fixedDelay=5000表示当前方法执行5000ms后,Spring调度会再次调用该方法publicvoidtestFixDelay(){logger.info("===fixedDelay:{}执行方法",固定延迟计数++);}@Scheduled(fixedRate=5000)//fixedRate=5000表示当前方法开始执行5000ms后,Spring调度会再次调用该方法publicvoidtestFixedRate(){logger.info("===fixedRate:{}执行方法",fixedRateCount++);}@Scheduled(initialDelay=1000,fixedRate=5000)//initialDelay=1000表示延迟1000ms执行第一个任务publicvoidtestInitialDelay(){logger.info("===initialDelay:{}thexecutionmethod",initialDelayCount++);}@Scheduled(cron="00/1***?")//cron接受cron表达式,根据cron表达式确定定时规则publicvoidtestCron(){logger.info("===initialDelay:{}times执行方式",cronCount++);}}使用@Scheduled创建计划任务。该注解用于标记定时任务方法。通过查看@Scheduled源码可以看出它支持多参数:cron:cron表达式,指定任务在特定时间执行;fixedDelay:表示在上次执行完成后,需要多长时间再次执行该任务,参数类型为long,单位为ms;fixedDelayString:含义同fixedDelay,只是参数类型改为String;fixedRate:表示任务以一定频率执行,参数类型为long,单位ms;fixedRateString:与fixedRate含义相同,只是将参数类型改为String;initialDelay:表示第一次执行任务前延迟多长时间,参数类型为long,单位ms;initialDelayString:与initialDelay同义,只是将参数类型改为String;zone:时区,默认为当前时区,一般不用。2、打开定时任务:packagecom.accord;导入org.springframework.boot.SpringApplication;导入org.springframework.boot.autoconfigure.SpringBootApplication;导入org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublicclassSpringBootCubron2Application{publicstaticvoidmain(String[]args){SpringApplication.run(SpringBootCron2Application.class,args);}}注意:这里的@EnableScheduling注解用于发现@Scheduled注解的任务并在后台执行。没有它,计划任务无法执行。引用官方文档原文:@EnableScheduling确保创建后台任务执行器。没有它,什么都无法安排。3、执行结果(单线程)完成一个简单的定时任务模型。下面执行springBoot观察执行结果:从控件平台输入的结果可以看出,所有的定时任务都是由同一个线程池中的同一个线程处理的,那么我们如何并发处理每个定时任务?请继续往下看。4、定时任务的多线程处理:看控制台输出的结果,所有的定时任务都是通过一个线程来处理的。估计在定时任务的配置里面设置了一个SingleThreadScheduledExecutor,于是看了源码,从ScheduledAnnotationBeanPostProcessor类开始一路找。果然,在ScheduledTaskRegistrar(定时任务注册类)中的ScheduleTasks中还有一个判断:this.taskScheduler=newConcurrentTaskScheduler(this.localExecutor);}这意味着如果taskScheduler为空,则为定时任务创建单线程线程池。该类中还有一个设置taskScheduler的方法:publicvoidsetScheduler(Objectscheduler){Assert.notNull(scheduler,"Schedulerobjectmustnotbenull");如果(调度程序instanceofTaskScheduler){这个。taskScheduler=(TaskScheduler)调度程序;}elseif(schedulerinstanceofScheduledExecutorService){this.taskScheduler=newConcurrentTaskScheduler(((ScheduledExecutor);}else{thrownewIllegalArgumentException("Unsupportedschedulertype:"+scheduler.getClass());}}这样问题就很简单了,我们只需要通过显式设置一个ScheduledExecutorService调用这个方法实现并发起来。我们要做的就是实现SchedulingConfigurer接口,重写configureTasks方法;包com.accord.task;导入org.springframework.context.annotation.Configuration;导入org.springframework.scheduling.annotation.SchedulingConfigurer;导入org。springframework.scheduling.config.ScheduledTaskRegistrar;导入java.util.concurrent.Executors;/***定时任务的多线程执行*@作者王久银*/@Configuration//所有定时任务都放在一个线程池中,定时任务在启动时使用不同的线程。publicclassScheduleConfigimplementsSchedulingConfigurer{@OverridepublicvoidconfigureTasks(ScheduledTaskRegistrartaskRegistrar){//设置一个长度为10的定时任务线程池taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));}}5.执行结果(并发)通过控制台输出的结果显示,每个定时任务都是由不同的线程处理的。来源:wangjiuyin.blog.csdn.net/article/details/79411952近期文章推荐:1.1,000+Java面试题及答案(2022最新版)2.精彩!Java协程来了。..3.SpringBoot2.x教程,太全面了!4.不要用爆破爆满画面,试试装饰者模式,这才是优雅的方式!!5.《Java开发手册(嵩山版)》最新发布,赶快下载吧!感觉不错,别忘了点赞+转发!
