学习quartz任务调度框架
介绍
Quartz 是什么?一文带你入坑 - 知乎 (zhihu.com)
- xxl job (大众点评 许雪里)
- elasticjob (依托zookeeper)
STEP
- 导入maven依赖
- 创建自定义Job类 实现Job 在execute中进行任务编写
- 创建任务调度工程工厂
- 创建定时器(startNow() or startAt(Date date))
- 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;
@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;
@Slf4j @RestController public class QuartzController {
@RequestMapping("/quartz/test") public void test() throws SchedulerException { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); JobDetail job = JobBuilder.newJob(TestJob.class) .withIdentity("testJob", "testJobGroup") .build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("testTrigger", "testTriggerGroup") .startNow() .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(10, 1)) .build(); scheduler.scheduleJob(job, trigger); scheduler.start(); } }
|
