在企业生产实践中,可能需要一些定时任务,如,月末或季末生成报表,这样就需要制定不同的定时任务。
SpringBoot中使用定时任务比较简单,在配置类或启动类上加入@EnableScheduling,并且在定时执行的方法上加入@Scheduled,如下:
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduleJob {
@Scheduled(fixedRate = 5000)//五秒执行一次
@Async
public void job()
{
System.out.println("doing job");
}
}
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
@Async注解是为了让他异步执行,相关内容可了解SpringBoot中的异步执行
@Scheduled注解详解:
配置项 | 类型 | 描述 |
---|---|---|
cron | String | 使用cron表达式定义任务执行时间 |
zone | String | 设置区域时间 |
fixedDelay | long | 从上一个任务完成到下一个任务开始时间间隔,单位毫秒 |
fixedDelayString | String | 与上一行相同,只是使用字符串 |
initialDelay | long | 容器初始化后,首次执行任务延迟时间,单位毫秒 |
initialDelayString | String | 与上一行相同,只是使用字符串 |
fixedRate | long | 上一个任务开始到下一个任务开始时间间隔,单位毫秒 |
fixedRateString | String | 与上一行相同,只是使用字符串 |
cron有6到7个空格分隔的时间元素,按顺序依次“秒 分 时 天 月 星期 年”,如 0 0 0 ? * WED 表示每个星期三00:00。*表示任意值,?不指定值,用于解决天和星期的冲突