SpringBoot Task自带的定时任务

一 Spring Task:Spring3.0以后自带的Task,可以将它看成一个轻量级的Quartz,使用起来比Quartz简单很多,在Spring应用中,直接使用@Scheduled注解即可,但对于集群项目比较麻烦,需要避免集群环境下任务被多次调用的情况,而且不能动态维护,任务启动以后不能修改、暂停等

二 TimerTask添加@EnableScheduling开启定时任务

packagecom.wan.timetaskmail;​
importorg.springframework.context.annotation.Configuration;
importorg.springframework.scheduling.annotation.EnableScheduling;
importorg.springframework.scheduling.annotation.Scheduled;

importjava.text.DateFormat;
importjava.util.Date;

@Configuration
@EnableScheduling// 启用定时任务
public class TimerTask{
static int num=1;

@Scheduled(cron="0/10 * * * * ?")// 每10秒执行一次
publicvoidscheduler() {
DateFormatdateFormat=DateFormat.getDateTimeInstance();
System.out.println("第"+(num++)+"次定时任务执行:"+dateFormat.format(newDate()));
   }
}

三 启动SpringBoot项目 定时任务生效

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。