任务调度框架

学习quartz任务调度框架

介绍

Quartz 是什么?一文带你入坑 - 知乎 (zhihu.com)

其他框架 —— 3千字带你搞懂XXL-JOB任务调度平台 (baidu.com)

  • xxl job (大众点评 许雪里)
  • elasticjob (依托zookeeper)

STEP

  1. 导入maven依赖
  2. 创建自定义Job类 实现Job 在execute中进行任务编写
  3. 创建任务调度工程工厂
  4. 创建定时器(startNow() or startAt(Date date))
  5. schedule.start()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.jcDemo.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
*@author:gao_quansui
*@user:ASUS
*@date:2022/9/29- 14:44
*@projectName:jc_demo
*/
@Slf4j
public class TestJob implements Job {
private static intindex= 1;

@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String data = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
log.info("第{}次执行 Timed Task, current time :{}",index++, data);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.jcDemo.controller.quartz;

import com.jcDemo.quartz.TestJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
*@author:gao_quansui
*@user:ASUS
*@date:2022/9/29- 14:47
*@projectName:jc_demo
*/
@Slf4j
@RestController
public class QuartzController {

@RequestMapping("/quartz/test")
public void test() throws SchedulerException {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// 定义任务调度实例, 并与TestJob绑定
JobDetail job = JobBuilder.newJob(TestJob.class)
.withIdentity("testJob", "testJobGroup")
.build();
// 定义触发器, 会马上执行一次, 接着5秒执行一次, 共十次
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("testTrigger", "testTriggerGroup")
.startNow()
.withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(10, 1))
.build();
// 使用触发器调度任务的执行
scheduler.scheduleJob(job, trigger);
// 开启任务
scheduler.start();
}
}

Untitled