Java 定时执行任务

1.开启Schedule

@SpringBootApplication
@ComponentScan(basePackages = {"com.emergen"})
//生成接口的实现类并注入到spring的容器中
@MapperScan("com.emergen.autogenerator.mapper")
@EnableScheduling
public class AutogeneratorApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(AutogeneratorApplication.class, args);
       // MyBean myBean=(MyBean)context.getBean("myBean",MyBean.class);
        //System.out.println(myBean.get());
        //RabbitAutoConfiguration
    }

}

2.编写定时执行组件,并加@Scheduled 注解

@Component
public class MyScheduled {

    @Scheduled(cron = "0/5 * * * * ?")
    public void execute(){
        Date day=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("MyScheduled 定时执行任务"+df.format(day));
    }
}

Cron 从左到右(用空格隔开):秒 分 小时 月份中的日期 月份 星期中的日期 年份

 

posted @ 2022-01-25 10:10  王叫兽  阅读(233)  评论(0)    收藏  举报