spring定时任务@Scheduled,异步操作@Async

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Smy_0114/article/details/83538881

需求时定时更新项目里面某一个设备的状态。

1.定时任务:spring定时任务@Scheduled(cron = "50 * * * * ? ")

2.更新状态采用异步更新,java默认是同步的,异步采用spring的@Async("async_update_gbStatus")

上代码spring配置xml实现定时任务,实现异步。

<!-- 计划任务配置,用 @Service @Lazy(false)标注类,
用@Scheduled(cron = "0 0 2 * * ?")标注方法 
1.pool-size:初始线程大小,3-10表示如果3个线程满足业务需求,则不会创建第四个,若满足不了
  则创建第四个最多10个。
2.keep-alive:当前线程执行完任务后,空闲的存活时间,0表示若空闲立即关闭,单位是秒。
3.queue-capacity:队列,当3个线程都在工作时候,就把多余的任务放在队列里面。
4.rejection-policy:报错解决方案。

-->
    <task:annotation-driven scheduler="scheduler" executor="executor" 
        proxy-target-class="true"/>
    <task:executor id="executor" pool-size="10"  />
    <task:executor id="async_update_gbStatus" pool-size="3-10" 
        queue-capacity="100" keep-alive="0" rejection-policy="CALLER_RUNS"/>
    <task:scheduler id="scheduler" pool-size="10" />

在需要定时的方法上面加入@Scheduled(cron = "50 * * * * ? ")

@Component//会把这个类注入到spring中管理
@Service
@Lazy(false)
public class Test1{
    @Scheduled(cron = "50 * * * * ? ") //50秒后执行
    public void gbStatus(){
        /*执行的异步方法,异步方法和当前调用的方法不能在同一个类中
            否则无法实现异步,官方文档有说明。*/
         asyncMethod();    
    }
}

在异步方法中加上@Async("async_update_gbStatus")括号里面的值和xml里面的id也就是这个标签task:executor的id值一致。

@service
public class Test2{
    @Async("async_update_gbStatus")//之前没加里面括号里面的值会一起很多线程,最后会出错
    public asycMethod(){
        // 业务       
    }

}

猜你喜欢

转载自blog.csdn.net/Smy_0114/article/details/83538881
今日推荐