使用Java Quartz有以下步骤:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
org.quartz.Job
接口,重写execute
方法来定义具体的任务逻辑。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!");
}
}
org.quartz.SimpleTrigger
或者org.quartz.CronTrigger
。import org.quartz.*;
public class MyTrigger {
public static void main(String[] args) throws SchedulerException {
// 创建JobDetail
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withIdentity("myJob", "group1")
.build();
// 创建Trigger,每隔一秒执行一次
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1))
.build();
// 创建Scheduler
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
// 绑定JobDetail和Trigger
scheduler.scheduleJob(jobDetail, trigger);
}
}
注意:需要确保Quartz的配置文件quartz.properties
在classpath下,或者手动配置org.quartz.scheduler.instanceName
、org.quartz.threadPool.threadCount
等属性。
以上是一个简单的Quartz使用示例,你可以根据自己的需求进行更复杂的配置和功能扩展。