springboot添加定时器@EnableScheduling

方法一:通过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 {}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值