1.在启动类上加入注解@EnableScheduling
package cn.stylefeng.guns;
import cn.stylefeng.roses.core.config.WebAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@EnableAsync //开启异步调用
@SpringBootApplication(exclude = {WebAutoConfiguration.class})
public class GunsApplication {
private final static Logger logger = LoggerFactory.getLogger(GunsApplication.class);
public static void main(String[] args) {
SpringApplication.run(GunsApplication.class, args);
logger.info(GunsApplication.class.getSimpleName() + " is success!");
}
}
2.定时任务,具体业务实现
package cn.stylefeng.guns.core.util;
import cn.stylefeng.guns.modular.airportManagement.basiclnfo.airportConfig.service.impl.RunwayTimeServiceImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.transaction.Transactional;
import java.util.List;
import java.util.TimerTask;
@Component
public class FlowTimer extends TimerTask {
private FlowService flowService = (FlowService) ApplicationContextUtil.getBean("flowService");
private RunwayTimeServiceImpl runwayTimeServiceImpl = (RunwayTimeServiceImpl) ApplicationContextUtil.getBean("runwayTimeServiceImpl");
@Override
@Async
@Scheduled(fixedDelay = 90000) //每1分半钟执行一次
public void run() {
System.out.print("*****");
}
}
3.配置类,将service实例化到定时器
package cn.stylefeng.guns.core.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}
4.完结