1.在启动类中加注解@EnableScheduling开启定时任务,让容器扫描时能扫描到 @Scheduled组件
package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author xuchuang
* @updateTime 2017年12月20日 下午3:53:53
*/
@SpringBootApplication
@EnableScheduling
public class App implements EmbeddedServletContainerCustomizer{
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(6636);
}
}
2.定义定时器:
package com.springboot.Test_myspringboot.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author xuchuang
* @updateTime 2018年1月5日 下午4:59:13
*/
@Component
public class ScheduleTest {
@Scheduled(cron = "0 0/1 * * * ?")
//@Scheduled(cron = "0 45 23 * * ?")
public void userDistributionStatistic() {
System.out.println("111111111");
}
}
其中@Component参考如下资料:
1、@controller 控制器(注入服务)
2、@service 服务(注入dao)
3、@repository dao(实现dao访问)
4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。
下面写这个是引入component的扫描组件
<context:component-scan base-package=”com.mmnc”>
其中base-package为需要扫描的包(含所有子包)
1、@Service用于标注业务层组件
2、@Controller用于标注控制层组件(如struts中的action)
3、@Repository用于标注数据访问组件,即DAO组件.
4、@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Service public class UserServiceImpl implements UserService { }
@Repository public class UserDaoImpl implements UserDao { } getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“***”) 这样来指定,这种bean默认是单例的,如果想改变,可以使用@Service(“beanName”)
@Scope(“prototype”)来改变。可以使用以下方式指定初始化方法和销毁方法(方法名任意): @PostConstruct public void init() { }
开始测试,启动项目,查看控制台: