前言

通过本文你将了解到如何在 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");@Overridepublic 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{@Overridepublic 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");@Overridepublic 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{@Overridepublic 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");@Overridepublic 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");@Autowiredprivate OrderService  orderService;//订单serviceprivate String serviceCode;//业务codepublic String getServiceCode() {return serviceCode;}public void setServiceCode(String serviceCode) {this.serviceCode = serviceCode;}@Overrideprotected 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 {@Beanpublic JobDetail simpleJobDetail() {return JobBuilder.newJob(SimpleJob.class).withIdentity("myJob").storeDurably().usingJobData("serviceCode","delete overdue orders").build();}@Beanpublic 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");@Autowiredprivate LiveReminderService  liveReminderService;//直播课提醒private String serviceCode;//业务code Live lesson reminderpublic 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 {@Autowiredprivate 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 {@Autowiredpublic CronSchedulerJobManger manger;@Overridepublic 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/

玩转 SpringBoot 2 之整合定时任务篇相关推荐

  1. 玩转 SpringBoot 2 之整合 WebSocket 篇

    前言 本文主要介绍如何在SpringBoot 2 中使用 WebSocket 的快速搭建教程,阅读前需要你必须了解如何搭建 SpringBoot 项目. 在搭建前先来了解一下什么是 WebSocket ...

  2. 玩转 SpringBoot 2 快速整合 | JSP 篇

    前言 JavaServer Pages(JSP)技术使Web开发人员和设计人员能够快速开发和轻松维护利用现有业务系统的信息丰富的动态Web页面.作为Java技术系列的一部分,JSP技术可以快速开发独立 ...

  3. 玩转 SpringBoot 2 快速整合 | Thymeleaf 篇

    前言 Thymeleaf是一个适用于Web和独立环境的现代服务器端Java模板引擎. Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板 - 可以在浏览器中正确显示的HTML,也可以用 ...

  4. 玩转 SpringBoot 2 快速整合 | FreeMarker篇

    FreeMarker 介绍 Apache FreeMarker™是一个模板引擎:一个Java库,用于根据模板和更改数据生成文本输出(HTML网页,电子邮件,配置文件,源代码等).模板是用FreeMar ...

  5. 玩转 SpringBoot 2 快速整合 | RESTful Api 篇

    概述 RESTful 是一种架构风格,任何符合 RESTful 风格的架构,我们都可以称之为 RESTful 架构.我们常说的 RESTful Api 是符合 RESTful 原则和约束的 HTTP ...

  6. 玩转 SpringBoot 2 之整合 JWT 下篇

    前言 在<玩转 SpringBoot 2 之整合 JWT 上篇> 中介绍了关于 JWT 相关概念和JWT 基本使用的操作方式.本文为 SpringBoot 整合 JWT 的下篇,通过解决 ...

  7. 玩转 SpringBoot 2 之整合 JWT 上篇

    前言 该文主要带你了解什么是 JWT,以及JWT 定义和先关概念的介绍,并通过简单Demo 带你了解如何使用 SpringBoot 2 整合 JWT. 介绍前在这里我们来探讨一下如何学习一门新的技术, ...

  8. 玩转 SpringBoot 2 快速整合 Filter 注解版

    前言 本文主要介绍如何在SpringBoot 2 中使用 Filter 的快速搭建教程,阅读前需要你必须了解 Filter 的基础使用以及如何搭建 SpringBoot 项目. 快速演示操作 第一步: ...

  9. 玩转 SpringBoot 2 快速整合 Listener

    前言 本文主要介绍如何在SpringBoot 2 中使用 Listener 的快速搭建教程,阅读前需要你必须了解 Listener 的基础使用以及如何搭建 SpringBoot 项目. 快速演示操作 ...

最新文章

  1. 解决:未找到setenv命令
  2. 回答我,停止 Goroutine 有几种方法?
  3. 移动端页面(响应式)
  4. 小波变换原理_基于电压行波原理故障测距的相关问题
  5. Ubuntu(Debian)apt-get
  6. React学习笔记 - 组件Props
  7. 数据浪潮之间的前端工程师
  8. PE格式详细讲解5 - 系统篇05|解密系列
  9. 如何从Java官网下载 Java API 文档
  10. Linux文件查看与查找命令
  11. 以太坊区块链中的数据结构
  12. 卫星高度角和方位角的计算
  13. leet code: Two Sum
  14. 安卓是属于全人类的还是谷歌的私有产品?
  15. wafw00f--一款基于python识别网站WAF的工具
  16. Hadoop详细入门知识
  17. 标题: 连接到服务器 ------------------------------ 无法连接到 DESKTOP-TGC5ASS\HAHA。 ----------------------------
  18. modeller建模
  19. Turbot4机器人入门教程-配置网络
  20. hibernate QBC和QBE精讲与案列分析(中)

热门文章

  1. python batch_size_深度学习中的batch的大小对学习效果有何影响?
  2. Docker部署MySQL5.7主从复制结构
  3. php eval 二进制,PHP eval函数使用介绍
  4. 容器安全 - 通过SECCOMP过滤在容器中的风险操作
  5. Linux 市场估值将超 70 亿美元,主要原因是安全与开源需求
  6. 如何在ASP.NET Core中建立有效的分页
  7. Orleans 3.0 发布,微软下一代云计算编程模式
  8. 使用Visual Studio 2017创建React项目
  9. stream 多个字段分组_Python Pandas对Excel数据的分组聚合和数据透视
  10. python如何制作一个任意列表_在Python中扁平化任意嵌套列表的最快方法是什么?...