Scheduled

Wu Jun 2019-12-25 15:59:03
Categories: > Tags:

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 支持多种参数:

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
    }
}