1. Quartz是定时任务的调度, 设置好触发时间和要调度的任务即可.
2 依赖
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
3 过程
(1) 编写任务类,实现Job接口
import java.util.Date; /**任务类, 实现job接口, 业务逻辑写在execte方法中 * author wmq * * @date 2020/12/615:56 */ public class HelloJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println(new Date() + "HelloJob execute"); } }
(2)应用
package com.qf; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; /** * author wmq * * @date 2020/12/79:22 */ public class CoreTriggerDemo { public static void main(String[] args) throws SchedulerException { // 调度器(核心组件, 调度触发器trigger执行任务jobDetail) Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); //触发器, 定义触发规则 // SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") // .startNow() // .withSchedule(SimpleScheduleBuilder.simpleSchedule() // .withIntervalInMilliseconds(100).withRepeatCount(0) // ) // .build(); CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trgger2", "group2") .withSchedule(CronScheduleBuilder.cronSchedule("*/2 * * * * ?")) .build(); //jobDetail实例 JobDetail jobDetail = JobBuilder.newJob(HelloJob.class) .withIdentity("job1", "group1") .build(); // 注册(将任务和触发器注册到调度器中) scheduler.scheduleJob(jobDetail, trigger); // 执行(启动调度器) scheduler.start(); } }
备注: cronSchedule表达式
* 任意
? 常用在周位 忽略
, 多个
/ 每隔 0/3在秒位上时表示: 从0秒开始, 每隔3秒执行一次
- 至 0-3 表示0秒1秒2秒 3秒
https://www.bejson.com/othertools/cron/网站是cron表达式的网站