springboot 定时调度

定时调度常用Timetask , QuartZ, Springtask。

Timetask由于时效性不好,很少作为企业级调度,而QuzrtZ开发太麻烦,所以使用Springtask进行配置。

新建一个定时调度的类,并使用注解方式进行调度

package cn.sona.microboot.task;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduler {
	@Scheduled(fixedRate = 2000) // 采用间隔调度,每2秒执行一次
	public void runJobA() { // 定义一个要执行的任务
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("【*** MyTaskA - 间隔调度 ***】"
		+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
						.format(new Date()));
	}
	@Scheduled(cron = "* * * * * ?") // 每秒调用一次
	public void runJobB() {
		System.err.println("【*** MyTaskB - 间隔调度 ***】"
		+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
						.format(new Date()));
	}
}

在程序启动的入口开启定时调度

package cn.sona.microboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication // 启动SpringBoot程序,而后自带子包扫描
@EnableScheduling	// 启用间隔调度
public class StartSpringBootMain {
	public static void main(String[] args) throws Exception {
		SpringApplication.run(StartSpringBootMain.class, args);
	}
}

此时调度有问题,因为现在调度是串行的,如果第一个调度事件太长,会影响第二个调度;

使用线程调度池进行调度。

package cn.sona.microboot.config;

import java.util.concurrent.Executors;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

@Configuration // 定时调度的配置类一定要实现指定的父接口
public class SchedulerConfig implements SchedulingConfigurer {
	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { 
		// 开启一个线程调度池
		taskRegistrar.setScheduler(Executors.newScheduledThreadPool(100));
	}

}

 效果如图所示

【*** MyTaskB - 间隔调度 ***】2017-09-30 01:03:43.003

【*** MyTaskB - 间隔调度 ***】2017-09-30 01:03:44.001

【*** MyTaskB - 间隔调度 ***】2017-09-30 01:03:45.003

【*** MyTaskB - 间隔调度 ***】2017-09-30 01:03:46.001

【*** MyTaskB - 间隔调度 ***】2017-09-30 01:03:47.005

【*** MyTaskA - 间隔调度 ***】2017-09-30 01:03:47.740

github地址:https://github.com/sona0402/springboot-task.git

猜你喜欢

转载自dan326714.iteye.com/blog/2395075