方法一:通过springboot自带入口来开启定时器。
首先我们都知道,springboot有一个自己的入口,也就是@SpringBootApplication(他是一个组合注解 由@Configuration,@EnableAutoConfiguration和@ComponentScan组成)。
首先定时器需要有一个总开关,因为我可能要定时很多函数,如果我想全都暂时关上总不能一个一个把注解给删掉吧。所以我们需要先把总开关打开,也就是在springboot的入口处添加@EnableScheduling这个注解。上代码(此为springboot的入口)
@Controller
@EnableCaching
@ImportResource({"classpath:dubbo-admin-api-customer.xml"})
@EnableWebMvc
@SpringBootApplication
@EnableScheduling
public class Application extends WebMvcConfigurerAdapter implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) throws Exception{
ApplicationContext app = SpringApplication.run(Application.class, args);
SpringManager.initContext(app);
}
@Override
public void run(String... args) throws Exception {
logger.info("服务启动完成!");
}
}
总开关添加好后,我们只需要对需要定时方法进行配置即可,使用注解@Scheduled(cron = "0/2 * * * * *") 后面为Cron表达式。表示每2秒执行一次。cron的具体语法我会一会贴在最后。
/**
* @Auther: liangbl
* @Date: 2018/8/29 09:59
* @Description:
*/
@Component
public class SchedulingConfig {
Logger logger=LoggerFactory.getLogger(getClass());
@Scheduled(cron = "0/5 * * * * ?") // 设置每5秒执行一次
public void getToken() {
logger.info("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
方法二:可能有的同学说,springboot我不喜欢加一堆乱七八糟的,我就要看着清晰、简洁。快活。OK 可以,有过基于xml开发经验的同学应该知道。使用定时器我只要在xml中做好配置,即可将我想要运行的方法按照我所配置的事件去运行,没错!但是springboot主张无xml,但是我们可以使用注解来让类变成xml,上代码。
@Configuration //证明这个类是一个配置文件
@EnableScheduling //打开quartz定时器总开关
public class Timer {}