以下是关于 quartz 定时任务(scheduler)的三种实现方式的伪原创文章内容:
Quartz 定时任务(Scheduler)的三种实现方式
一、引入依赖包
首先,需要在项目中引入必要的 JAR 包。这些包包括 Spring 框架和 Quartz 调度器的相关依赖。
org.springframework spring-context-support org.quartz-scheduler quartz 2.2.1 org.quartz-scheduler quartz-jobs 2.2.1
二、实现方式一
- 定义定时任务的业务逻辑
首先,定义一个实现了 Job 接口的类,用于执行定时任务的具体业务逻辑。
package gentle.test;import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.Date;
/**
@author silence
@date 2018/7/17 11:37 */ @Service("show") public class Show implements Job { private static Logger _log = LoggerFactory.getLogger(Show.class);
@Override public void execute(JobExecutionContext arg0) throws JobExecutionException { _log.info("\n\n-------------------------------\n " + "It is running and the time is : " + new Date() + "\n-------------------------------\n"); } }
- 声明定时任务并关联业务实现类
在
JobDetail jb = JobBuilder.newJob(Show.class)中,关联业务类。package gentle.test;
import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.Date;
/**
@author silence
@date 2018/7/17 11:36 */ @Service("schedulerTest") public class SchedulerTest { private static Logger _log = LoggerFactory.getLogger(Scheduler.class);
public static void main(String[] args) { try { // 1. 创建 Scheduler 的工厂 SchedulerFactory sf = new StdSchedulerFactory(); // 2. 从工厂中获取调度器实例 Scheduler scheduler = sf.getScheduler(); // 3. 创建 JobDetail JobDetail jb = JobBuilder.newJob(Show.class) // Show 为一个 job,是要执行的一个任务。 .withDescription("这是我的测试定时任务。") // job 的描述 .withIdentity("jy2Job", "jy2Group") // job 的 name 和 group .build(); // 任务运行的时间,SimpleSchedle 类型触发器有效 long time = System.currentTimeMillis() + 3 1000L; // 3 秒后启动任务 Date statTime = new Date(time); // 4. 创建 Trigger // 使用 SimpleScheduleBuilder 或者 CronScheduleBuilder Trigger t = TriggerBuilder.newTrigger() .withDescription("") .withIdentity("jyTrigger", "jyTriggerGroup") //.withSchedule(SimpleScheduleBuilder.simpleSchedule()) .startAt(statTime) // 默认当前时间启动 , 也可以写为:.startNow(); .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * ?")) // 每两秒执行一次 .build(); // 5. 注册任务和定时器 scheduler.scheduleJob(jb, t); // 6. 启动调度器 scheduler.start(); _log.info("启动时间 : " + new Date()); } catch (Exception e) { _log.info("定时任务出现异常 : " + e); } } }
- 运行成功

三、实现方式二
- 定义定时任务的业务逻辑
与实现方式一相同,定义一个实现了
Job接口的类,用于执行定时任务的具体业务逻辑。package gentle.test;
import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.Date;
/**
@author silence
@date 2018/7/17 11:37 */ @Service("show") public class Show implements Job { private static Logger _log = LoggerFactory.getLogger(Show.class);
@Override public void execute(JobExecutionContext arg0) throws JobExecutionException { _log.info("\n\n-------------------------------\n " + "It is running and the time is : " + new Date() + "\n-------------------------------\n"); } }
- 定义定时任务的触发类,调用业务类中的实现
创建一个触发类,用于调用业务类中的实现。
package gentle.test;
import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; import java.text.SimpleDateFormat; import java.util.Date;
public class UserSyncTask { private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
Show show;
public void cronDepartmentsAndUsersJob() {
logger.info("\n\n 定时--开始,当前时间: " + dateFormat().format(new Date()));
try {
show.execute(null);
} catch (JobExecutionException e) {
e.printStackTrace();
}
logger.info("\n\n 定时--结束,当前时间:" + dateFormat().format(new Date()));
}
private SimpleDateFormat dateFormat() {
return new SimpleDateFormat("HH:mm:ss");
}}
- 在配置文件中配置触发类和任务执行频率
在配置文件中设置触发类和任务的执行频率。
https://www.php.cn/link/383d86008edae3a3a7e68c59c0da6dbe" xmlns:task="https://www.php.cn/link/5de6755473dc988fe6c7db81f26a53ac" xmlns:util="https://www.php.cn/link/8474b8609e772af467ac0fc4acad4dd4" xmlns:xsi="https://www.php.cn/link/1fb425070298bc615c24b69845387662" xsi:schemaLocation="https://www.php.cn/link/383d86008edae3a3a7e68c59c0da6dbehttps://www.php.cn/link/383d86008edae3a3a7e68c59c0da6dbe/spring-beans.xsdhttps://www.php.cn/link/8474b8609e772af467ac0fc4acad4dd4https://www.php.cn/link/8474b8609e772af467ac0fc4acad4dd4/spring-util.xsdhttps://www.php.cn/link/5de6755473dc988fe6c7db81f26a53achttps://www.php.cn/link/5de6755473dc988fe6c7db81f26a53ac/spring-task.xsd">
- 运行成功

四、实现方式三
- 引入依赖包
与实现方式一相同,引入必要的 JAR 包。
- 在运行类中添加两个注解
在运行类中添加 @EnableScheduling 和 @Scheduled 注解。
package gentle.test;import gentle.util.DateUtil; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date;
/**
定时任务 -- 简版
@author silence
@date 2018/7/31 16:03 */ @Component // 注册为一个 bean @EnableScheduling // 开启定时器 public class Sender { private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
@Scheduled(fixedDelay = 2000) // 每 2s 执行一次。 public void send() { logger.info(" \n------------------------\n " + "定时任务内容 :" + DateUtil.dateFormat().format(new Date()) + "\n------------------------\n"); } }
- 运行效果

PS:第三种实现方式最为简单。
源码地址:定时任务demo










