Quartz定时任务Demo

24

Maven依赖

<!-- 定时任务的计划 -->
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
</dependency>
<!-- 定时任务的任务 -->
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.2.1</version>
</dependency>

包结构

各类代码

TimingTask

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class TimingTask implements Job {

  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    // TODO: 2021/10/25 具体执行的任务方法
    task();
  }

  public void task() {
    System.out.println(System.currentTimeMillis());
  }
}

TimingTaskScheduler

import com.example.scheduledtask.quartz.job.TimingTask;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.ParseException;

public class TimingTaskScheduler {

  /** 创建调度器的方法 */
  public Scheduler getScheduler() throws SchedulerException {
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    return schedulerFactory.getScheduler();
  }

  /** 定义任务方法 */
  public void schedulerJob(String cron) throws ParseException, SchedulerException {
    // 创建任务
    JobDetail jobDetail = JobBuilder.newJob(TimingTask.class).withIdentity("Task", "task").build();
    CronTrigger trigger =
        TriggerBuilder.newTrigger()
            .withIdentity("Task", "task")
            .withSchedule(CronScheduleBuilder.cronSchedule(cron))
            .build();
    Scheduler scheduler = getScheduler();
    // 调度任务
    scheduler.scheduleJob(jobDetail, trigger);
    // 开始任务
    scheduler.start();
  }
}

StartTimingTask

import com.example.scheduledtask.quartz.scheduler.TimingTaskScheduler;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 它会随着Springboot的启动而运行它的run方法
 *
 * <p>args就是Springboot启动的参数
 */
@Component
public class StartTimingTask implements CommandLineRunner {
  @Override
  public void run(String... args) {
    TimingTaskScheduler timingTaskScheduler = new TimingTaskScheduler();
    String cron = "* * * * * ?";
    try {
      timingTaskScheduler.schedulerJob(cron);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}