定时任务执行方法
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
@Slf4j
public class SyncTask{
@Scheduled(cron = "0/5 * * * * ?")
public void dataSyncTask() {
log.info("Second scheduled task is starting... ...");
log.info("Second scheduled task is ending... ...");
}
}
这里发布后会遇到单线程不执行的问题
添加Config
import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
/**
* @Auther: Wangtianming
* @Date: 2021/10/9 18:19
* @Description:
*/
@EnableScheduling
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
// 将定时任务的单线程改成多线程
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
Method[] methods = BatchProperties.Job.class.getMethods();
int defaultPoolSize = 3;
int corePoolSize = 0;
if (methods != null && methods.length > 0) {
for (Method method : methods) {
Scheduled annotation = method.getAnnotation(Scheduled.class);
if (annotation != null) {
corePoolSize++;
}
}
if (defaultPoolSize > corePoolSize)
corePoolSize = defaultPoolSize;
}
scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize));
}
}