package com.nokia.alarm.config;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import com.nokia.alarm.service.AlarmSaveToGPandPGService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@SuppressWarnings("null")
public class SchedulingConfig implements SchedulingConfigurer {

    @Value("${scheduling.scheduler.pool.size:2}")
    private int poolSize;

    @Autowired
    private AlarmSaveToGPandPGService service;

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        // 使用最常用的ThreadPoolTaskScheduler
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        // 线程数
        taskScheduler.setPoolSize(poolSize);
        taskScheduler.setRemoveOnCancelPolicy(true);
        taskScheduler.setThreadNamePrefix("taskSchedulerThreadPool-");
        log.info("已完成 ThreadPoolTaskScheduler 配置, poolSize = {}", poolSize);
        return taskScheduler;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskScheduler());
        taskRegistrar.addCronTask(() -> {
            Date date = new Date();
            service.newAlarm(date);
            service.updateAlarm(date);
        }, "0 */5 * * * ?");
    }

}
