1 @Scheduled
@EnableScheduling 注解,启用定时任务的配置
@SpringBootApplication
@EnableScheduling
public class Application {
}
创建定时任务实现类
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 5000)
public void xxx() {
//...
}
@Scheduled(cron = "${jobs.cron}")
public void xxx() {
//...
}
}
@Scheduled 支持多种参数:
- cron:cron表达式,指定任务在特定时间执行;
- fixedDelay:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;
- fixedDelayString:与fixedDelay含义一样,只是参数类型变为String;
- fixedRate:表示按一定的频率执行任务,参数类型为long,单位ms;
- fixedRateString: 与fixedRate的含义一样,只是将参数类型变为String;
- initialDelay:表示延迟多久再第一次执行任务,参数类型为long,单位ms;
- initialDelayString:与initialDelay的含义一样,只是将参数类型变为String;
- zone:时区,默认为当前时区,一般没有用到。
2 ScheduledExecutorService
通过 ScheduledExecutorService 周期性地运行
private ScheduledExecutorService m_executorService;
private void schedulePeriodicRefresh() {
this.m_executorService.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
//...
}
}, 1000,
1000,
SECONDS
);
}
3 多线程 Scheduled
@Configuration
@EnableScheduling
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
}
}
或者
@Configuration
@EnableScheduling
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class ScheduleConfig {
@Bean("schedulePool")
public Executor jobPool() {
ThreadPoolTaskScheduler exec = new ThreadPoolTaskScheduler();
exec.setPoolSize(10);
exec.initialize();
return exec;
}
}
public class ScheduleService {
@Async("schedulePool")
@Scheduled(fixedRate = 20000 )
public void readSecondComponent() {
// body
}
}