玩转 SpringBoot 2 之整合定时任务篇

前言

通过本文你将了解到如何在 SpringBoot 2 中整合定时任务使用教程,具体详细内容如下:

  • SpringBoot 自带定时任务使用教程
  • SpringBoot 集成 JDK 定时任务使用教程
  • SpringBoot 集成 quartz 使用教程

阅读前需要你必须了解如何搭建 SpringBoot 项目。

SpringBoot 自带定时任务使用教程

使用 SpringBoot 自带的任务调度拢共需要2步:

第一步:在SpringBoot 启动类上声明 @EnableScheduling,具体代码如下:


@SpringBootApplication
@EnableScheduling
public class SpringbootlearnApplication {
	private static final Logger log = LoggerFactory.getLogger(SpringbootexamplesApplication.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	public static void main(String[] args) {
		SpringApplication.run(SpringbootexamplesApplication.class, args);
		 log.info("reportCurrentTimeInitialDelay fixedRate The time is start {}", dateFormat.format(new Date()));
	}
}

Spring Bean 方法上声明 @Scheduled 并在注解中指定启动的规则,具体代码如下:

@Component
public class SchedulerTask {
	
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	//固定的时间执行 也就是 5秒执行一次
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTimeFixedRate() {
    	try {
			Thread.sleep(6*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        log.info("reportCurrentTimeFixedRate The time is now {}", dateFormat.format(new Date()));
    }
}

测试结果:

fixedRate: 任务执行的时间是6秒,设置任务时间间隔5秒,实际按每6秒执行一次。

2019-11-17 18:32:46.484  INFO 128312 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 18:32:46
2019-11-17 18:32:52.428  INFO 128312 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:32:52
2019-11-17 18:32:58.428  INFO 128312 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:32:58
2019-11-17 18:33:04.428  INFO 128312 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:33:04
2019-11-17 18:33:10.429  INFO 128312 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:33:10
2019-11-17 18:33:16.429  INFO 128312 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:33:16

fixedRate: 任务执行的时间是3秒,设置任务时间间隔5秒执行一次,实际按每5秒执行一次。

2019-11-17 18:38:34.210  INFO 127372 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 18:38:34
2019-11-17 18:38:37.148  INFO 127372 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:38:37
2019-11-17 18:38:42.145  INFO 127372 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:38:42
2019-11-17 18:38:47.145  INFO 127372 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:38:47
2019-11-17 18:38:52.147  INFO 127372 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:38:52
2019-11-17 18:38:57.147  INFO 127372 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeFixedRate The time is now 18:38:57

任务执行的时间通过在 SchedulerTask 的 reportCurrentTimeFixedRate 方法中通过Thread.sleep(6*1000)来实现。而任务时间间隔通过 fixedRate 来进行设置 5000 就是 5秒

Scheduled 注解经常使用参数设置项:

  • fixedRate :固定的时间执行 也就是 多少秒执行一次。 这个上面的代码已介绍。
  • fixedDelay:执行完毕后再过5秒后执行。
  • initialDelay:启动后延迟多少秒后执行 不能单独使用。

fixedDelayinitialDelay 设置项的 Demo 案例:


@SpringBootApplication
@EnableScheduling
public class SpringbootlearnApplication {
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); 
	public static void main(String[] args) {
		SpringApplication.run(SpringbootlearnApplication.class, args);
		 log.info("reportCurrentTimeInitialDelay fixedRate The time is start {}", dateFormat.format(new Date()));
	}
}


@Component
public class SchedulerTask {
	
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(initialDelay=0, fixedDelay=5000)
    public void reportCurrentTimeInitialDelay() {
    	try {
			Thread.sleep(6*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        log.info("reportCurrentTimeInitialDelay fixedRate The time is now {}", dateFormat.format(new Date()));
    }
	
}

测试结果:

fixedDelay:任务执行的时间是6秒,设置任务执行完后时5秒后在执行,实际按每11秒执行一次

2019-11-17 18:47:28.977  INFO 130308 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 18:47:28
2019-11-17 18:47:54.916  INFO 130308 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:47:54
2019-11-17 18:48:05.918  INFO 130308 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:48:05
2019-11-17 18:48:16.920  INFO 130308 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:48:16
2019-11-17 18:48:27.923  INFO 130308 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:48:27

fixedDelay:任务执行的时间是3秒,设置任务执行完后时5秒后在执行,实际按每8秒执行一次

2019-11-17 18:57:10.370  INFO 129352 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 18:57:10
2019-11-17 18:57:33.306  INFO 129352 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:57:33
2019-11-17 18:57:41.308  INFO 129352 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:57:41
2019-11-17 18:57:49.310  INFO 129352 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:57:49
2019-11-17 18:57:57.312  INFO 129352 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:57:57
2019-11-17 18:58:05.314  INFO 129352 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:58:05
2019-11-17 18:58:13.317  INFO 129352 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:58:13
2019-11-17 18:58:21.319  INFO 129352 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : reportCurrentTimeInitialDelay fixedRate The time is now 18:58:21

同时 Scheduled 还支持 cron 表达式方式,具体是用方式如下:

@Component
public class SchedulerTaskForCron {
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	/**
	 * 每天的14:00 执行一次
	 */
	@Scheduled(cron="0 0 14 * * ?")
	private void cron() {
		 log.info("cron The time is now {}", dateFormat.format(new Date()));
	}
	
	/**
	 * 每5秒执行一次
	 */
	@Scheduled(cron="0/5 * * * * ?")
	private void cron2() {
		try {
			Thread.sleep(6*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		log.info("cron2 The time is now {}", dateFormat.format(new Date()));
	}
}

测试结果:

任务执行的时间是6秒 设置任务时间间隔5秒 实际按每10秒执行一次

2019-11-17 19:10:47.072  INFO 132132 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 19:10:47
2019-11-17 19:10:56.001  INFO 132132 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : cron2 The time is now 19:10:56
2019-11-17 19:11:06.000  INFO 132132 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : cron2 The time is now 19:11:06
2019-11-17 19:11:16.002  INFO 132132 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : cron2 The time is now 19:11:16
2019-11-17 19:11:26.003  INFO 132132 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : cron2 The time is now 19:11:26
2019-11-17 19:11:36.001  INFO 132132 --- [   scheduling-1] cn.lijunkui.task.own.SchedulerTask       : cron2 The time is now 19:11:36

关于cron使用规则 网上有很多在线生成工具 例如:http://www.bejson.com/othertools/cron/

SpringBoot 集成 JDK 定时任务使用教程

Timer 方式

第一步:定义定时任务多线程 Demo 程序,继承TimerTask并实现 run 方法,具体代码如下:

public class DemoTask extends TimerTask{
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	@Override
	public void run() {
		try {
			Thread.sleep(4*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		 log.info("DemoTask The time is now {}", dateFormat.format(new Date()));
	}

}

然后通过Timer 的 schedule 方法完成定时任务的操作,具体代码如下:


public class TimerManger {
	private DemoTask demoTask;
	public TimerManger(DemoTask demoTask) {
		this.demoTask = demoTask;
	}
	public void run() throws ParseException {
		Timer timer = new Timer();
	
		long intevalPeriod = 3 * 1000;
		long delay = 0;
		//该方法是冲现在时间开始每3秒执行一次
		timer.schedule(demoTask, new Date(), intevalPeriod);
	}
}

最后定义项目启动就执行的 Runner 程序,具体代码如下:

package cn.lijunkui.task.jdk;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value = 1)
public class DemoTaskRunner implements ApplicationRunner{

	@Override
	public void run(ApplicationArguments args) throws Exception {
		TimerTest test = new TimerTest(new DemoTask());
		test.run();
	}
}

测试结果:

schedule: DemoTask 任务执行时间是4秒 设置的时间间隔是3秒 我们的任务是每4秒执行一次

2019-11-17 20:49:14.712  INFO 139860 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 20:49:14
2019-11-17 20:49:18.712  INFO 139860 --- [        Timer-0] cn.lijunkui.task.own.SchedulerTask       : DemoTask The time is now 20:49:18
2019-11-17 20:49:22.712  INFO 139860 --- [        Timer-0] cn.lijunkui.task.own.SchedulerTask       : DemoTask The time is now 20:49:22
2019-11-17 20:49:26.713  INFO 139860 --- [        Timer-0] cn.lijunkui.task.own.SchedulerTask       : DemoTask The time is now 20:49:26

scheduleAtFixedRate: DemoTask 任务执行时间是4秒 设置的时间间隔是3秒 我们的任务是每4秒执行一次

scheduleAtFixedRate 使用方式如下:

long intevalPeriod = 3 * 1000;
long delay = 0;
timer.scheduleAtFixedRate(demoTask, delay, intevalPeriod);
2019-11-17 20:59:48.670  INFO 141724 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 20:59:48
2019-11-17 20:59:52.669  INFO 141724 --- [        Timer-0] cn.lijunkui.task.own.SchedulerTask       : DemoTask The time is now 20:59:52
2019-11-17 20:59:56.670  INFO 141724 --- [        Timer-0] cn.lijunkui.task.own.SchedulerTask       : DemoTask The time is now 20:59:56
2019-11-17 21:00:00.670  INFO 141724 --- [        Timer-0] cn.lijunkui.task.own.SchedulerTask       : DemoTask The time is now 21:00:00
2019-11-17 21:00:04.671  INFO 141724 --- [        Timer-0] cn.lijunkui.task.own.SchedulerTask       : DemoTask The time is now 21:00:04

scheduleAtFixedRate:任务执行时间是2秒 设置的时间间隔是3秒 我们的任务是每3秒执行一次,这里就不在进行演示了。任务执行时间通过 Thread.sleep(4*1000) 来实现。

ScheduledExecutorService 方式

Java SE5 java.util.concurrent 里 ScheduledExecutorService 提供了新的任务调度的方式。他是采用线程池的方式来执行的,相对于 Timer 语法更为简单。

第一步:定义定时任务多线程 Demo 程序,通过实现Runnable 并重写run 方法,具体代码如下:


public class ScheduledExecutorTask implements Runnable{
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	@Override
	public void run() {
		try {
			Thread.sleep(4*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		 log.info("scheduledExecutorTask The time is now {}", dateFormat.format(new Date()));
	}
}

第二步:通过Executors.newSingleThreadScheduledExecutor() 创建 ScheduledExecutorService 然后在通过ScheduledExecutorService 的schedule方法调用定时任务。具体代码如下:

package cn.lijunkui.task.jdk.scheduledExecutorService;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTest {
	private ScheduledExecutorTask task;
	public ScheduledExecutorTest(ScheduledExecutorTask task) {
		this.task = task;
	}
	public void run() {
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 
	    service.schedule(task, 3, TimeUnit.SECONDS);
	}
}

最后定义项目启动就执行的 Runner 程序,具体代码如下:

@Component
@Order(value = 1)
public class TimerMangerRunner implements ApplicationRunner{

	@Override
	public void run(ApplicationArguments args) throws Exception {
		ScheduledExecutorTest test = new ScheduledExecutorTest(new ScheduledExecutorTask());
		test.run();
	}
}

测试结果:

schedule:任务执行时间是2秒 设置的时间间隔是3秒 我们的任务是每5秒执行一次

2019-11-27 04:48:02.818  INFO 17196 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 04:48:02
2019-11-27 04:48:07.825  INFO 17196 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:48:07

schedule:任务执行时间是4秒 设置的时间间隔是3秒 我们的任务是每7秒执行一次,并且是只执行一次

2019-11-27 04:39:19.202  INFO 15416 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 04:39:19
2019-11-27 04:39:26.208  INFO 15416 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:39:26

scheduleAtFixedRate: 任务执行时间是2秒 设置的时间间隔是3秒 我们的任务是每3秒执行一次

public class ScheduledExecutorTest {

	private ScheduledExecutorTask task;
	public ScheduledExecutorTest(ScheduledExecutorTask task) {
		this.task = task;
	}
	public void run() {
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 
	   service.scheduleAtFixedRate(task, 0, 3, TimeUnit.SECONDS);
	}
}
public class ScheduledExecutorTest {

	private ScheduledExecutorTask task;
	public ScheduledExecutorTest(ScheduledExecutorTask task) {
		this.task = task;
	}
	public void run() {
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 
	   service.scheduleAtFixedRate(task, 0, 3, TimeUnit.SECONDS);
	}
}
2019-11-27 04:51:01.243  INFO 14972 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:51:01
2019-11-27 04:51:04.246  INFO 14972 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:51:04
2019-11-27 04:51:07.244  INFO 14972 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:51:07
2019-11-27 04:51:10.246  INFO 14972 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:51:10

scheduleAtFixedRate: 任务执行时间是4秒 设置的时间间隔是3秒 我们的任务是每4秒执行一次

public class ScheduledExecutorTest {

	private ScheduledExecutorTask task;
	public ScheduledExecutorTest(ScheduledExecutorTask task) {
		this.task = task;
	}
	public void run() {
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 
	   service.scheduleAtFixedRate(task, 0, 3, TimeUnit.SECONDS);
	}
}
public class ScheduledExecutorTask  implements Runnable{
	private static final Logger log = LoggerFactory.getLogger(ScheduledExecutorTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	@Override
	public void run() {
		try {
			Thread.sleep(4*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		 log.info("scheduledExecutorTask The time is now {}", dateFormat.format(new Date()));
	}
}
2019-11-27 04:53:13.951  INFO 15928 --- [           main] c.l.SpringbootexamplesApplication        : Started SpringbootexamplesApplication in 2.939 seconds (JVM running for 4.356)
2019-11-27 04:53:13.963  INFO 15928 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 04:53:13
2019-11-27 04:53:17.966  INFO 15928 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:53:17
2019-11-27 04:53:21.968  INFO 15928 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:53:21
2019-11-27 04:53:25.970  INFO 15928 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:53:25
2019-11-27 04:53:29.973  INFO 15928 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:53:29

scheduleWithFixedDelay : 任务执行时间是2秒 设置的时间间隔是3秒 我们的任务是每5秒执行一次

public class ScheduledExecutorTest {

	private ScheduledExecutorTask task;
	public ScheduledExecutorTest(ScheduledExecutorTask task) {
		this.task = task;
	}
	public void run() {
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 
	    service.scheduleWithFixedDelay(task,0, 3, TimeUnit.SECONDS);
	}
}
2019-11-27 04:58:38.039  INFO 17332 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 04:58:38
2019-11-27 04:58:40.042  INFO 17332 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:58:40
2019-11-27 04:58:45.048  INFO 17332 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:58:45
2019-11-27 04:58:50.053  INFO 17332 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:58:50

scheduleWithFixedDelay : 任务执行时间是4秒 设置的时间间隔是3秒 我们的任务是每7秒执行一次

2019-11-27 04:56:26.884  INFO 13576 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 04:56:26
2019-11-27 04:56:30.883  INFO 13576 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:56:30
2019-11-27 04:56:37.890  INFO 13576 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:56:37
2019-11-27 04:56:44.895  INFO 13576 --- [pool-1-thread-1] c.l.t.j.s.ScheduledExecutorTask          : scheduledExecutorTask The time is now 04:56:44

通过上面测试scheduleAtFixedRate 和 scheduleWithFixedDelay
我们建议使用scheduleAtFixedRate 因为他的时间间隔更为合理。

SpringBoot 集成 quartz 使用教程

SpringBoot 2.0 已经有了 快速集成 quartz 的 starter 依赖。

第一步:我们先引入quartz starter 依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

第二步:定义quartz 的 job,也就是具体执行的任务。具体代码如下:

package cn.lijunkui.task.quartz.simple;

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

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import cn.lijunkui.task.own.SchedulerTask;
import cn.lijunkui.task.quartz.simple.service.OrderService;

public class SimpleJob  extends QuartzJobBean{
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	@Autowired
	private OrderService  orderService;//订单service
	private String serviceCode;//业务code
	

	public String getServiceCode() {
		return serviceCode;
	}
	public void setServiceCode(String serviceCode) {
		this.serviceCode = serviceCode;
	}

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		
		System.out.println(serviceCode);
		 log.info("quartz simple The time is now {}", dateFormat.format(new Date()));
		orderService.delete();
	}

}

第三步:创建 quartz 的 Config 同时定义 JobDetail 和 触发器 Trigger

package cn.lijunkui.task.quartz.simple;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SimpleJobConfig {
	@Bean
	public JobDetail simpleJobDetail() {
		
		return JobBuilder.newJob(SimpleJob.class).withIdentity("myJob").storeDurably()
				 	.usingJobData("serviceCode","delete overdue orders")
	                .build();
	}
	@Bean
	public Trigger simpleJobTrigger() {
		//定义每三秒执行一次
		SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever();
		//定义触发器
		return TriggerBuilder.newTrigger().forJob(simpleJobDetail()).withIdentity("myJobTrigger").withSchedule(simpleScheduleBuilder).build();
	}
}

第四步:定义注入的Job的Service

package cn.lijunkui.task.quartz.simple.service;

import org.springframework.stereotype.Service;

@Service
public class OrderService {
	public void delete() {
		try {
			Thread.sleep(6*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("delete data sucess....");
	}
}

测试结果:

orderService延时 2秒 任务是按照每3秒执行一次

2019-11-27 05:06:15.245  INFO 4496 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 05:06:15
delete data sucess....
delete overdue orders
2019-11-27 05:06:17.586  INFO 4496 --- [eduler_Worker-2] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:06:17
delete data sucess....
delete overdue orders
2019-11-27 05:06:20.583  INFO 4496 --- [eduler_Worker-3] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:06:20
delete data sucess....
delete overdue orders
2019-11-27 05:06:23.585  INFO 4496 --- [eduler_Worker-4] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:06:23
delete data sucess....
delete overdue orders
2019-11-27 05:06:26.582  INFO 4496 --- [eduler_Worker-5] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:06:26
delete data sucess....
delete overdue orders
2019-11-27 05:06:29.584  INFO 4496 --- [eduler_Worker-6] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:06:29
delete data sucess....
delete overdue orders

orderService延时 6秒 任务是按照每3秒执行一次

2019-11-27 05:03:18.333  INFO 3128 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path '/sbe'
2019-11-27 05:03:18.341  INFO 3128 --- [           main] c.l.SpringbootexamplesApplication        : Started SpringbootexamplesApplication in 2.712 seconds (JVM running for 4.122)
2019-11-27 05:03:18.345  INFO 3128 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 05:03:18
delete overdue orders
2019-11-27 05:03:20.786  INFO 3128 --- [eduler_Worker-2] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:03:20
delete overdue orders
2019-11-27 05:03:23.775  INFO 3128 --- [eduler_Worker-3] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:03:23
delete data sucess....
delete overdue orders
2019-11-27 05:03:26.774  INFO 3128 --- [eduler_Worker-4] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:03:26
delete data sucess....
delete overdue orders
delete data sucess....
2019-11-27 05:03:29.775  INFO 3128 --- [eduler_Worker-5] cn.lijunkui.task.own.SchedulerTask       : quartz simple The time is now 05:03:29
delete overdue orders
delete data sucess....

quartz 使用cron 表达式

cron 表达式操作方式和上面的基本一致,不同的是需要实现 Job 而不是使用继承的方式,具体代码如下:


public class CronJob implements Job{
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	@Autowired
	private LiveReminderService  liveReminderService;//直播课提醒
	private String serviceCode;//业务code Live lesson reminder

	public String getServiceCode() {
		return serviceCode;
	}
	public void setServiceCode(String serviceCode) {
		this.serviceCode = serviceCode;
	}
    @Override  
    public void execute(JobExecutionContext context) throws JobExecutionException {
    	log.info("quartz cron The time is now {}", dateFormat.format(new Date()));
    	System.out.println("CronJob"+serviceCode);
    	liveReminderService.sendmessage();
    } 
}

JobDetail 和 触发器 Trigger的manger类和上面定义的Config操作基本一致,区别在与CronScheduleBuilder 来创建触发器。具体代码如下:

@Component
public class CronSchedulerJobManger {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    
    public void scheduleJobs() throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduleJob(scheduler);  
    }  
    
    private void scheduleJob(Scheduler scheduler) throws SchedulerException{
        JobDetail jobDetail = JobBuilder.newJob(CronJob.class) .withIdentity("job1", "group1")
        		.usingJobData("serviceCode","Live lesson reminder1").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail,cronTrigger);   
    }  
      
}

定义直播课提醒的 Service

package cn.lijunkui.task.quartz.cron.service;

import org.springframework.stereotype.Service;

@Service
public class LiveReminderService {
	public void sendmessage() {
		try {
			Thread.sleep(4*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
}

定义启动类 使项目一启动就执行 CronSchedulerJobManger 的定时任务。

package cn.lijunkui.task.quartz.cron;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CronSchedulerRunner implements CommandLineRunner {
	@Autowired
	public CronSchedulerJobManger manger;
	@Override
	public void run(String... args) throws Exception {
		manger.scheduleJobs();
	}

}

测试结果:

任务执行时间4秒 定时任务设置时间间隔 5秒 实际执行效果是每5秒执行一次

2019-11-27 06:16:33.104  INFO 4268 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 06:16:33
2019-11-27 06:16:35.029  INFO 4268 --- [eduler_Worker-1] cn.lijunkui.task.own.SchedulerTask       : quartz cron The time is now 06:16:35
2019-11-27 06:16:40.002  INFO 4268 --- [eduler_Worker-2] cn.lijunkui.task.own.SchedulerTask       : quartz cron The time is now 06:16:40
2019-11-27 06:16:45.003  INFO 4268 --- [eduler_Worker-3] cn.lijunkui.task.own.SchedulerTask       : quartz cron The time is now 06:16:45
2019-11-27 06:16:50.011  INFO 4268 --- [eduler_Worker-4] cn.lijunkui.task.own.SchedulerTask       : quartz cron The time is now 06:16:50

任务执行时间10秒 定时任务设置时间间隔 5秒 实际执行效果是每5秒执行一次

2019-11-27 06:17:48.662  INFO 22904 --- [           main] c.l.SpringbootexamplesApplication        : reportCurrentTimeInitialDelay fixedRate The time is start 06:17:48
2019-11-27 06:17:50.044  INFO 22904 --- [eduler_Worker-1] cn.lijunkui.task.own.SchedulerTask       : quartz cron The time is now 06:17:50
2019-11-27 06:17:55.005  INFO 22904 --- [eduler_Worker-2] cn.lijunkui.task.own.SchedulerTask       : quartz cron The time is now 06:17:55
2019-11-27 06:18:00.013  INFO 22904 --- [eduler_Worker-3] cn.lijunkui.task.own.SchedulerTask       : quartz cron The time is now 06:18:00

小结

SpringBoot 自带定时任务,JDK 、quartz 使用各有千秋,在实际工作中你可以根据自己的喜好自行选择使用任一种方式进行定时任务的开发。如果上述操作你都还没有接触过,还等什么赶紧操作起来!

代码示例

我本地环境如下:

  • SpringBoot Version: 2.1.0.RELEASE
  • Apache Maven Version: 3.6.0
  • Java Version: 1.8.0_144
  • IDEA:Spring Tools Suite (STS)

整合过程如出现问题可以在我的GitHub 仓库 springbootexamples 中模块名为 spring-boot-2.x_task 项目中进行对比查看

GitHub:https://github.com/zhuoqianmingyue/springbootexamples

参考文献

http://spring.io/guides/gs/scheduling-tasks/

发布了136 篇原创文章 · 获赞 502 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/ljk126wy/article/details/103111265