Back End

Quartz定时任务Demo

PineappleCat · 10月25日 · 2021年 19次已读

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();
    }
  }
}

Click here to view the copyright notice of this site(点击此处查看本站版权声明)
0 条回应

必须 注册 为本站用户, 登录 后才可以发表评论!