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

通过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;

@Service
public class TaskListener implements InitializingBean {

	@Resource(name = "xxxService")
	private XxxService service;

	@Override
	public 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值