刚刚看了下Spring Boot实现定时任务的文章,感觉还不错。Spring Boot 使用Spring自带的Schedule来实现定时任务变得非常简单和方便。在这里个大家分享下。
开启缓存注解
-
@SpringBootApplication
-
@EnableScheduling //开启定时任务
-
public class Application {
-
public static void main(String[] args) {
-
SpringApplication.run(Application.class, args);
-
}
-
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
编写定时任务
-
@Component
-
public class ScheduledTasks {
-
private Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
-
// cron接受cron表达式,根据cron表达式确定定时规则
-
@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次
-
public void testCron() {
-
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-
logger.info(sdf.format(new Date())+"*********每5秒执行一次");
-
}
-
}
任务完成
启动项目,查看控制台打印信息,发现定时任务已经生效。spring boot 和Scheduled整合完毕。
74万+

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



