在Spring Boot中使用@Scheduled实现定时任务

在Spring Boot中使用@Scheduled实现定时任务

以前没有使用Spring Boot的Java风格配置的时候,用XML配置过@Scheduled定时任务,如今都习惯使用Java风格配置了,在此简单记录 
一下Spring Boot的@Scheduled定时任务的实现过程。ide

1. 添加@EnableScheduling注解到入口类声明上面,以下所示:

@SpringBootApplication
@EnableScheduling
public class FooApplication extends SpringBootServletInitializer{
    ...
}

 

2. 将@Scheduled添加到不带参数的方法上,以下所示:

@Component
public class ScheduleTaskService implements IScheduleTaskService {

    @Override
    @Scheduled(fixedRate = 6000)
    public void autosync() {
        System.out.print(".");
    }

}

 

其中@Scheduled注解后面括号里面能够指定各类参数,在上面代码里面的fixedRate = 6000意思是下面的任务每隔6000毫秒,即每隔6秒执行一次。 
下面简单提一下cron表达式,举个例子:spa

@Scheduled(cron = "0 0 3 * * ?")  //天天凌晨3:00执行任务

 

cron表达式中各时间元素使用空格进行分割,分别表示以下含义:
按顺序依次为
秒(0~59)
分钟(0~59)
小时(0~23)
天(月)(0~31,可是你须要考虑你月的天数)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
7.年份(1970-2099)code

相关文章
相关标签/搜索