springboot 启动时执行单次任务

 

 最近做任务遇到一个问题,需要在项目启动时候执行扫描数据库表的任务,用于异常恢复容灾,一开始想的是可不可以使用定时任务

代码如下 并且在启动类加上

@EnableScheduling注解就可以实现定时去执行任务了 
package com.beihui.service.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class XXXTask {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Scheduled(cron = "0 0 0 * * ?")
    public void bTask() {
        long startCurrentTime = System.currentTimeMillis();
        logger.info("开始执行定时任务:" + startCurrentTime);
        //业务处理
        long endTime = System.currentTimeMillis();
        logger.info("定时任务:执行结束,花费时间" + (endTime - startCurrentTime));
    }


    @Scheduled(cron = "0 */1 * * * ?")
    public void runUpdateDbTask() {
        long startCurrentTime = System.currentTimeMillis();
        logger.info("开始执行更新数据库剩余次数定时任务:" + startCurrentTime);
       //业务处理
        long endTime = System.currentTimeMillis();
        logger.info("定时任务:执行结束,花费时间" + (endTime - startCurrentTime));
    }

    @Scheduled(fixedDelay = 60 * 1000 * 10)
    public void cTask() {
        long startCurrentTime = System.currentTimeMillis();
       //业务处理

        long endTime = System.currentTimeMillis();
        logger.info("定时任务:执行结束,花费时间" + (endTime - startCurrentTime));
    }

}

 

但是这个并不能单次执行任务,所以后来 使用listener

代码如下,并在启动类加上

@ServletComponentScan注解 
package xx.xx.xx;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class XXXListener implements ServletContextListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


//项目启动执行
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        long startTime = System.currentTimeMillis();
        logger.info("开始执行启动任务,{}"+startTime);
        //业务处理
        long endTime = System.currentTimeMillis();
        logger.info("执行启动任务结束,共花费时间{}"+(startTime-endTime));
    }

//项目终止时执行
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值