项目启动后开启定时任务方法-->InitializingBean

来源:互联网 发布:黑客在淘宝上的暗语 编辑:程序博客网 时间:2024/05/16 08:21

通过springframework自带的InitializingBean同样可以达到项目启动后开启定时任务效果,具体实现如下。

1.写一个继承InitializingBean接口的类

import java.util.Calendar;import java.util.Date;import java.util.Timer;import javax.annotation.Resource;import org.springframework.beans.factory.InitializingBean;import org.springframework.stereotype.Service;import com.xxx.service.XxxService;import com.xxx.util.StringUtil;@Servicepublic class TaskListener implements InitializingBean {@Resource(name = "xxxService")private XxxService service;@Overridepublic void afterPropertiesSet() throws Exception {Calendar date = Calendar.getInstance();//设置时间为 xx-xx-xx 00:00:00        date.set(date.get(Calendar.YEAR),        date.get(Calendar.MONTH), date.get(Calendar.DATE), 14, 52, 0);        //如果第一次执行定时任务的时间 小于当前的时间            //此时要在 第一次执行定时任务的时间加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。        if (date.before(new Date())) {            date.set(date.get(Calendar.YEAR),            date.get(Calendar.MONTH), date.get(Calendar.DATE) + 1, 14, 52, 0);            }        StringUtil.date2String(date.getTime(), "yyyy-MM-dd HH:mm:ss");        Timer timer = new Timer();XxxTask task = new Xxxask(service);timer.scheduleAtFixedRate(task, date.getTime(), 24 * 60 * 60 * 1000);}}
2.在配置文件中配置该类

<bean class="com.xxx.task.TaskListener" />
这样就行了。

原理:

Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下三种:
1)通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
2)通过 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;
3)在指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。
结论:Bean在实例化的过程中
Constructor > @PostConstruct > InitializingBean > init-method


0 0
原创粉丝点击