1.启动类中增加注解@EnableScheduling
2.新建定时类,增加@Component("jobs")注解,纳入spring管理
3.类中增加@Scheduled(cron="0 * * * * ? ") 定时配置
4.cron 类似linux的crontab 第一个参数秒,第二个分,第三个小时
代码如下
@SpringBootApplication
@EnableAutoConfiguration
@EnableScheduling
@MapperScan(basePackages ="com.asiainfo.selenuim.dao")
@ComponentScan(basePackages ="com.asiainfo.selenuim")
public class Main {
protected static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
logger.debug("spring启动成功");
}
}
@Component("jobs")
public class Jobs {
protected static final Logger logger = LoggerFactory.getLogger(Jobs.class);
@Autowired
SmsService smsService;
@Scheduled(cron="0 * * * * ? ")
public void test(){
System.out.println("当前时间"+new java.util.Date());
}
}

本文介绍如何在Spring Boot项目中配置并使用定时任务。主要步骤包括:在启动类中添加@EnableScheduling注解;创建带有@Component注解的定时任务类;在类的方法上使用@Scheduled注解来设置cron表达式。
1260

被折叠的 条评论
为什么被折叠?



