spring提供了@scheduled注解來(lái)實(shí)現(xiàn)定時(shí)任務(wù)
需要注意的幾點(diǎn):
1庐船、spring的@Scheduled注解 嗅虏,需要寫(xiě)在實(shí)現(xiàn)上固歪、
2躲胳、定時(shí)器的任務(wù)方法不能有返回值(有返回值的場(chǎng)景去google)
3蜓洪、定時(shí)器是單線程的
優(yōu)點(diǎn):實(shí)現(xiàn)中出現(xiàn)exception或者error沒(méi)有捕獲的情況,并不會(huì)導(dǎo)致線程退出坯苹,只會(huì)導(dǎo)致本次執(zhí)行中斷退出隆檀,下一次還會(huì)再執(zhí)行。
缺點(diǎn):?jiǎn)尉€程的情況下粹湃,如果有多個(gè)方法都被注解了恐仑,就會(huì)排隊(duì)執(zhí)行。
例如为鳄,存在run(),test()兩個(gè)方法裳仆,都用注解間隔5s執(zhí)行一次的方式執(zhí)行,實(shí)際執(zhí)行會(huì)是
run()-5s-test()-5s-run()孤钦,也就是說(shuō)兩次執(zhí)行之間間隔了10s;
如果run()方法執(zhí)行完畢就要8s歧斟,則會(huì)呈現(xiàn)run()-8s-test()-5s-run()
兩次執(zhí)行間隔了13s
可以通過(guò)改配置的方式實(shí)現(xiàn)任務(wù)并行執(zhí)行。
xmlns 多加下面的內(nèi)容
<xmlns:task="http://www.springframework.org/schema/task" >
xsi:schemaLocation多加下面的內(nèi)容
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
然后配置pool-size來(lái)設(shè)定多少并發(fā)
<task:scheduler id="myScheduler1" pool-size="2"/>
如上就會(huì)有2個(gè)線程來(lái)執(zhí)行定時(shí)任務(wù)了偏形。
springboot中静袖,通過(guò)下面注解來(lái)引入xml配置文件
@SpringBootApplication
@EnableScheduling
@ImportResource("classpath*:sch.xml")
@Component("MyTest")
public class MyTest{
……
}
也可以不用@Scheduled注解,直接用xml配置俊扭,一個(gè)完整的xml示例
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<task:scheduler id="myScheduler1" />
<task:scheduler id="myScheduler2" />
<task:scheduled-tasks scheduler="myScheduler1">
<task:scheduled ref="MyTest" method="test1" fixed-delay="2000"/>
<task:scheduled ref="MyTest" method="test2" fixed-delay="2000"/>
</task:scheduled-tasks>
<task:scheduled-tasks scheduler="myScheduler2">
<task:scheduled ref="MyTest" method="test3" fixed-delay="5000"/>
</task:scheduled-tasks>
</beans>