源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

SpringBoot定时任务两种(Spring Schedule 与 Quartz 整合 )实现方法

  • 时间:2022-08-21 05:38 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:SpringBoot定时任务两种(Spring Schedule 与 Quartz 整合 )实现方法
[b]前言[/b] 最近在项目中使用到定时任务,之前一直都是使用Quartz 来实现,最近看Spring 基础发现其实Spring 提供 Spring Schedule 可以帮助我们实现简单的定时任务功能。 下面说一下两种方式在Spring Boot 项目中的使用。 [b]Spring Schedule 实现定时任务[/b] Spring Schedule 实现定时任务有两种方式 1. 使用XML配置定时任务, 2. 使用 @Scheduled 注解。 因为是Spring Boot 项目 可能尽量避免使用XML配置的形式,主要说注解的形式. [b]Spring Schedule 提供三种形式的定时任务:[/b] [b]固定等待时间 @Scheduled(fixedDelay = 时间间隔 )[/b]
@Component
public class ScheduleJobs {
  public final static long SECOND = 1 * 1000;
  FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");


  @Scheduled(fixedDelay = SECOND * 2)
  public void fixedDelayJob() throws InterruptedException {
    TimeUnit.SECONDS.sleep(2);
    System.out.println("[FixedDelayJob Execute]"+fdf.format(new Date()));
  }
}
[b]固定间隔时间 @Scheduled(fixedRate = 时间间隔 )[/b]
@Component
public class ScheduleJobs {
  public final static long SECOND = 1 * 1000;
  FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");


  @Scheduled(fixedRate = SECOND * 4)
  public void fixedRateJob() {
    System.out.println("[FixedRateJob Execute]"+fdf.format(new Date()));
  }
}
[b]Corn表达式 @Scheduled(cron = Corn表达式)[/b]
@Component
public class ScheduleJobs {
  public final static long SECOND = 1 * 1000;
  FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");


  @Scheduled(cron = "0/4 * * * * ?")
  public void cronJob() {
    System.out.println("[CronJob Execute]"+fdf.format(new Date()));
  }
}

[b]Spring Boot 整合 Quartz 实现定时任务[/b] [b]添加Maven依赖[/b]
    <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
    </dependency>
[b]Spring Boot 整合 Quartz[/b] Spring 项目整合 Quartz 主要依靠添加 SchedulerFactoryBean 这个 FactoryBean ,所以在maven 依赖中添加 spring-context-support 。 首先添加 QuartzConfig 类 来声明相关Bean
@Configuration
public class QuartzConfig {
  @Autowired
  private SpringJobFactory springJobFactory;

  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() {
    SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
    schedulerFactoryBean.setJobFactory(springJobFactory);
    return schedulerFactoryBean;
  }

  @Bean
  public Scheduler scheduler() {
    return schedulerFactoryBean().getScheduler();
  }
}

这里我们需要注意 我注入了一个 自定义的JobFactory ,然后 把其设置为SchedulerFactoryBean 的 JobFactory。其目的是因为我在具体的Job 中 需要Spring 注入一些Service。  所以我们要自定义一个jobfactory, 让其在具体job 类实例化时 使用Spring 的API 来进行依赖注入。 SpringJobFactory 具体实现:
@Component
public class SpringJobFactory extends AdaptableJobFactory {

  @Autowired
  private AutowireCapableBeanFactory capableBeanFactory;

  @Override
  protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
    Object jobInstance = super.createJobInstance(bundle);
    capableBeanFactory.autowireBean(jobInstance);
    return jobInstance;
  }
}

具体使用 (摘取自项目代码):
@Service
public class QuartzEventServiceImpl implements QuartzEventService {
  private static final String JOB_GROUP = "event_job_group";
  private static final String TRIGGER_GROUP = "event_trigger_group";
  @Autowired
  private Scheduler scheduler;

  @Override
  public void addQuartz(Event event) throws SchedulerException {
    JSONObject eventData = JSONObject.parseObject(event.getEventData());
    Date triggerDate = eventData.getDate("date");
    JobDetail job = JobBuilder.newJob(EventJob.class).withIdentity(event.getId().toString(), JOB_GROUP).usingJobData(buildJobDateMap(event)).build();
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity(event.getId().toString(), TRIGGER_GROUP).startAt(triggerDate).build();
    scheduler.scheduleJob(job, trigger);
  }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部