最近做任务遇到一个问题,需要在项目启动时候执行扫描数据库表的任务,用于异常恢复容灾,一开始想的是可不可以使用定时任务
代码如下 并且在启动类加上
@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) {
}
}