很多时候,我们有这么一个需求,需要在每天的某个固定时间或者每隔一段时间让应用去执行某一个任务。为了实现这个需求,通常我们会通过多线程来实现这个功能,但是这样我们需要自己做一些比较麻烦的工作。接下来,让我们看看如何使用spring scheduling task简化定时任务功能的实现。
添加maven依赖为了方便展示,我们使用spring boot来简化我们的spring配置。因为我们使用的是spring自带的scheduling,因此我们只需要引入最进本的spring-boot-starter即可。
org.springframework.boot spring-boot-starter-parent 1.2.5.release 1.8 org.springframework.boot spring-boot-starter 注意,spring boot需要jdk8的编译环境。
创建scheduled task让我们创建一个scheduletask来实现我们的需求:
@componentpublic class scheduledtask { private static final simpledateformat dateformat = new simpledateformat(yyyy-mm-dd hh:mm:ss); private integer count0 = 1; private integer count1 = 1; private integer count2 = 1; @scheduled(fixedrate = 5000) public void reportcurrenttime() throws interruptedexception { system.out.println(string.format(---第%s次执行,当前时间为:%s, count0++, dateformat.format(new date()))); } @scheduled(fixeddelay = 5000) public void reportcurrenttimeaftersleep() throws interruptedexception { system.out.println(string.format(===第%s次执行,当前时间为:%s, count1++, dateformat.format(new date()))); } @scheduled(cron = */5 * * * * *) public void reportcurrenttimecron() throws interruptedexception { system.out.println(string.format(+++第%s次执行,当前时间为:%s, count2++, dateformat.format(new date()))); }}可以看到,我们在我们真正需要执行的方法上添加了@scheduled标注,表示这个方法是需要定时执行的。
在@scheduled标注中,我们使用了三种方式来实现了同一个功能:每隔5秒钟记录一次当前的时间:
fixedrate = 5000表示每隔5000ms,spring scheduling会调用一次该方法,不论该方法的执行时间是多少
fixeddelay = 5000表示当方法执行完毕5000ms后,spring scheduling会再次调用该方法
cron = */5 * * * * * *提供了一种通用的定时任务表达式,这里表示每隔5秒执行一次。
配置scheduling接下来我们通过spring boot来配置一个最简单的spring web应用,我们只需要一个带有main方法的类即可:
[]()
@springbootapplication@enableschedulingpublic class app { public static void main(string[] args) { springapplication.run(app.class, args); }}我们先来看看class上的标注:
@springbootapplication 实际上是了以下三个标注的集合:
@configuration 告诉spring这是一个配置类,里面的所有标注了@bean的方法的返回值将被注册为一个bean
@enableautoconfiguration 告诉spring基于class path的设置、其他bean以及其他设置来为应用添加各种bean
@componentscan 告诉spring扫描class path下所有类来生成相应的bean
@enablescheduling 告诉spring创建一个task executor,如果我们没有这个标注,所有@scheduled标注都不会执行
通过以上标注,我们完成了schedule的基本配置。最后,我们添加main方法来启动一个spring boot应用即可。
测试在根目录下执行命令:mvn spring-boot:run,我们可以看到:
LTCC生瓷层压中腔体的形变评价及控制方法
科捷机器人打造钢帘线生产车间自动物流系统,开启自动化时代
随着机器学习技术不断深入,人工智能在医疗领域的前景更加开阔
电力监控系统在酒店项目中的设计与应用
AMEYA360:Panasonic松下HF系列压敏电阻器
如何使用Spring scheduling task简化定时任务功能的实现?
基于芯片的AI摄影到底有哪些体验呢?
第三十二颗北斗导航卫星发射成功,备份星助力北斗服务能力发展
差分放大器计算公式讲解
农业物联网的应用现状和产业化的新路径
信号发生器N5183B_40G维修案例
信阳中部半导体项目正式投产 2019年销售额预计可达3.5亿元
生物医药因为有了区块链技术有了什么新的发展
三星推出了新的Galaxy S21系列和其他设备
中美摩擦若成“长征”,谁是这场战役的最大得利者?
iPhone 15系列若限充电速度或违法?
小米手表为什么到现在还不支持iOS系统
智能音箱代表的,是否为足够浩瀚的蓝海市场?
围观八类网络跳线性能优势
Agilent N9330B手持式天馈线测试仪