Redis作为存储的Quartz调度器作业库指南
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzExample {
public static void main(String[] args) {
try {
// 创建Scheduler
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
// 创建JobDetail
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withIdentity("myJob", "group1")
.build();
// 创建Trigger
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever())
.build();
// 将JobDetail和Trigger加入Scheduler
scheduler.scheduleJob(jobDetail, trigger);
// 启动Scheduler
scheduler.start();
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}
class MyJob implements org.quartz.Job {
public MyJob() {
}
public void execute(org.quartz.JobExecutionContext context) throws org.quartz.JobExecutionException {
System.out.println("执行任务: " + System.currentTimeMillis());
}
}
这段代码演示了如何使用Quartz定时任务调度框架来创建并执行一个简单的定时任务。首先,创建了Scheduler对象,然后定义了一个JobDetail和一个触发器,并将它们加入到Scheduler中。最后启动Scheduler开始执行任务。这个例子简单明了,适合作为学习Quartz的入门教程。
评论已关闭