我们可能会在服务中增加一些定时任务,这时候可能就会用到Spring中的@EnableScheduling,例如下面的代码。
Main类中启动SpringFramework的IoC容器。
package com.woods.schedule;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author Woods
* Created on 2021-02-02
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext configApplicationContext =
new AnnotationConfigApplicationContext(Config.class);
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
}
CronService中处理我们的定时任务
package com.woods.schedule;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
* @author Woods
* Created on 2021-02-02
*/
@Service
@EnableScheduling
public class CronService {
@Scheduled(cron = "*/2 * * * * *")
public void print2() {
System.out.println(LocalDateTime.now() + " print2");
}
@Scheduled(cron = "*/3 * * * * *")
public void print1() throws InterruptedException {
System.out.println(LocalDateTime.now() + " print1");
// 模拟方法阻塞
TimeUnit.SECONDS.sleep(60);
System.out.println("sleep done print1");
}
}
Config是配置类。
package com.woods.schedule;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author Woods
* Created on 2021-02-02
*/
@Configuration
@ComponentScan("com.woods.schedule")
public class Config {
}
由于只有一个线程执行print2方法和print1方法,因此如果某个方法执行的慢,会造成其他方法的阻塞。生产环境中美滋滋地这样写完,容易造成问题。。
正确的写法是用一个线程池来处理CronService中的各个方法,如下所示。
package com.woods.schedule;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
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 org.springframework.stereotype.Service;
/**
* @author Woods
* Created on 2021-02-02
*/
@Service
@EnableScheduling
public class CronServiceWithThreadPool implements SchedulingConfigurer {
@Scheduled(cron = "*/3 * * * * *")
public void print1() throws InterruptedException {
System.out.println(LocalDateTime.now() + " print1");
TimeUnit.SECONDS.sleep(60);
System.out.println("sleep done print1");
}
@Scheduled(cron = "*/2 * * * * *")
public void print2() {
System.out.println(LocalDateTime.now() + " print2");
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(2));
}
}
PS:这里的(Executors.newScheduledThreadPool(2)只是一个例子,生产环境请自定义线程池或者用公司封装好的线程池。