quartz countJob 实例
所属分类 quartz
浏览量 79
独立使用 ,不依赖spring
pom依赖
org.quartz-scheduler:quartz:2.3.0
使用RAMJobStore,job信息存储在内存中 ,
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
没有quartz.properties配置文件时,quartz默认使用 RAMJobStore
quartz job默认无状态 ,每次调用都会创建一个新的 JobDataMap
job实现类加上注解 @PersistJobDataAfterExecution
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicLong;
@PersistJobDataAfterExecution
public class CountJob implements Job {
private static final Logger log = LoggerFactory.getLogger(CountJob.class);
private static final AtomicLong ID = new AtomicLong(0);
private final String name;
public CountJob(){
name = "CountJob_"+ID.incrementAndGet();
}
@Override
public void execute(JobExecutionContext context) {
final String COUNT = "count";
Long count = (Long) context.getJobDetail().getJobDataMap().get(COUNT);
if(count==null){
count = 1L;
}
System.out.println(name+" run,count="+count+",now="+LocalDateTime.now());
count = count + 1;
context.getJobDetail().getJobDataMap().put(COUNT, count);
}
}
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.util.concurrent.TimeUnit;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
public class QuartzDemo {
public static void main(String[]args)throws Exception{
// 1.创建调度器
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
// 2.创建JobDetail实例,并与CountJob类绑定
JobDetail job = JobBuilder.newJob(CountJob.class)
.withIdentity("countJob", "countGroup")
.build();
// 3.构建Trigger实例,每隔3s执行一次
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("countJobTrigger", "countGroup")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(3)
.repeatForever())
.build();
// 4.执行,开启调度器
scheduler.scheduleJob(job, trigger);
System.out.println(System.currentTimeMillis());
scheduler.start();
//主线程睡眠1分钟,然后关闭调度器
TimeUnit.MINUTES.sleep(1);
scheduler.shutdown();
System.out.println(System.currentTimeMillis());
}
}
https://gitee.com/dyyx/work2024/blob/master/demo/quartz/quartzdemo/src/main/java/demo/QuartzDemo.java
上一篇
下一篇
mac brew 安装 openjdk17
quartz 原理简介
Quartz简介
quartz 配置文件 quartz.properties
Kafka 时间轮 TimingWheel
mysql 悲观锁