标签:doc 不同 reads artifact text obb 2.0 inter scheduler
原文 https://blog.csdn.net/wqh8522/article/details/79224290
1. 使用Timer
public class TestTimer { public static void main(String[] args) { TimerTask timerTask = new TimerTask() { @Override public void run() { System.out.println("task run:"+ new Date()); } }; Timer timer = new Timer(); //安排指定的任务在指定的时间开始进行重复的固定延迟执行。这里是每3秒执行一次 timer.schedule(timerTask,10,3000); } }
2.ScheduledExecutorService
public class TestScheduledExecutorService { public static void main(String[] args) { ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); // 参数:1、任务体 2、首次执行的延时时间 // 3、任务执行间隔 4、间隔时间单位 service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+new Date()), 0, 3, TimeUnit.SECONDS); } }
3.多线程执行
@Configuration //config包中加 @EnableAsync public class AsyncConfig { /* 此处成员变量应该使用@Value从配置中读取 */ private int corePoolSize = 10; private int maxPoolSize = 200; private int queueCapacity = 10; @Bean public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.initialize(); return executor; } }
然后在定时任务的类或者方法上添加@Async
我们在方法上使用@Scheduled注解来设置任务的执行时间,并且使用三种属性配置方式:
initialDelay
, 定义该任务延迟执行时间。springboot2.0之后的
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
else
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
public class TestQuartz extends QuartzJobBean {
/**
* 执行定时任务
* @param jobExecutionContext
* @throws JobExecutionException
*/
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("quartz task "+new Date());
}
}
@Configuration
public class QuartzConfig {
@Bean
public JobDetail teatQuartzDetail(){
return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build();
}
@Bean
public Trigger testQuartzTrigger(){
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(10)
//设置时间周期单位秒
.repeatForever();
return TriggerBuilder.newTrigger().forJob(teatQuartzDetail()) .withIdentity("testQuartz") .withSchedule(scheduleBuilder) .build();
}
}
标签:doc 不同 reads artifact text obb 2.0 inter scheduler
原文地址:https://www.cnblogs.com/lhblog1994/p/9716186.html