Quartz Java Scheduler Guide
To use Quartz in Java, you need to first import the Quartz dependencies, then create a Scheduler object, and use the Scheduler object to create tasks and triggers, and associate them together.
Here is a simple example:
- Add the Quartz dependency package.
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
- Create a task class that implements the Job interface and execute method, in which you write the necessary logic for the task to be executed.
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("Hello, Quartz!");
}
}
- Create a Trigger object and specify the time rule for when the task should be executed.
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.CronScheduleBuilder;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
public class Main {
public static void main(String[] args) {
try {
// 创建任务
JobDetail job = JobBuilder.newJob(MyJob.class)
.withIdentity("myJob")
.build();
// 创建触发器,每隔一秒执行一次
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger")
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
.build();
// 创建调度器
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.start();
// 将任务和触发器关联起来
scheduler.scheduleJob(job, trigger);
} catch (Exception e) {
e.printStackTrace();
}
}
}
With the code above, we have created a simple Quartz application that executes a task to print “Hello, Quartz!” every second. You can adjust the task’s execution time and logic according to your own needs.