Spring boot 多线程执行Spring定时任务
程序员文章站
2022-05-01 17:19:35
...
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
/**
* 多线程执行定时任务
* 所有的定时任务都放在一个线程池中,定时任务启动时使用不同都线程
*/
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(10);
taskScheduler.initialize();
taskRegistrar.setTaskScheduler(taskScheduler);
}
}
import java.io.IOException;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
//@Configuration
//@EnableScheduling // 可以在启动类上注解也可以在当前文件
public class TestJob {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Scheduled(cron = "0 0 0/1 * * ?")
public void runfirst() throws IOException {
logger.info("********first job is begin******" + new Date());
long timeLong1 = System.currentTimeMillis();
long timeLong2 = System.currentTimeMillis();
logger.info("============time11111111===========" + (timeLong2 - timeLong1));
logger.info("********first job is ok******" + new Date());
}
@Scheduled(fixedDelay=2000)
public void runThird() {
logger.info("********third job is ok*******" + new Date());
}
}
上一篇: DIV居中的经典方法