超级简单!Spring中四种霸气定时任务实现方式

        当涉及到定时任务的实现,Spring框架提供了多种强大的选项,以适应各种需求。在这篇文章中,我们将介绍Spring中的几种不同方式来实现定时任务,包括使用@Scheduled注解、SchedulingConfigurer接口、TaskScheduler和集成Quartz框架。

一、使用@Scheduled注解

        1.创建一个Spring Boot应用。

        2.创建一个定时任务类,使用@Scheduled注解定义要执行的任务。在这个示例中,我们将每隔5秒打印一次当前时间。

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {

    @Scheduled(fixedRate = 5000) // 每隔5秒执行一次
    public void printCurrentTime() {
        System.out.println("Current time: " + System.currentTimeMillis());
    }
}

        3.在Spring Boot的入口类上添加@EnableScheduling注解以启用定时任务

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

        4.运行应用,你将看到定时任务每隔5秒打印当前时间到控制台。

二、使用SchedulingConfigurer接口

  1. 创建一个Spring Boot应用。

  2. 创建一个SchedulingConfigurer的实现类,自定义定时任务的配置。在这个示例中,我们配置一个每隔3秒执行一次的任务。

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

@Configuration
public class CustomSchedulingConfigurer implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addFixedRateTask(
            () -> System.out.println("Custom Task: " + System.currentTimeMillis()),
            3000
        );
    }
}

        3.在Spring Boot的入口类上添加@EnableScheduling注解以启用定时任务。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

        4.运行应用,你将看到定时任务每隔3秒执行一次,打印当前时间到控制台。

三、使用TaskScheduler

TaskScheduler是Spring提供的任务调度器接口,允许你以编程方式定义和管理定时任务。
示例代码:

  1. 创建一个Spring Boot应用。

  2. 配置TaskScheduler并创建定时任务。在这个示例中,我们将使用ThreadPoolTaskScheduler作为任务调度器,定时每隔2秒执行一个任务。

  3. import org.springframework.context.annotation.Bean;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
    import org.springframework.scheduling.support.CronTrigger;
    import org.springframework.stereotype.Component;
    import org.springframework.scheduling.TaskScheduler;
    
    @Component
    public class ScheduledTasks {
    
        @Bean
        public TaskScheduler taskScheduler() {
            ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
            taskScheduler.setPoolSize(5);
            return taskScheduler;
        }
    
        @Scheduled(fixedRate = 2000) // 每隔2秒执行一次
        public void scheduledTask() {
            System.out.println("Scheduled Task: " + System.currentTimeMillis());
        }
    }

        3.在Spring Boot的入口类上添加@EnableScheduling注解以启用定时任务。

        4.运行应用,你将看到定时任务每隔2秒执行一次,打印当前时间到控制台。

四、使用Quartz

Quartz是一个强大的任务调度框架,Spring支持将Quartz集成到应用中以实现更复杂的定时任务需求。
示例代码:

  1. 创建一个Spring Boot应用。

  2. 添加Quartz的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

        3.创建一个Quartz的Job类,实现org.quartz.Job接口,并在execute方法中定义任务逻辑。

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

public class MyQuartzJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("Quartz Job: " + System.currentTimeMillis());
    }
}

        4.创建一个配置类,配置Quartz的调度器和触发器,以及Job的细节。

import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {
    @Bean
    public JobDetail quartzJobDetail() {
        return JobBuilder.newJob(MyQuartzJob.class)
                .withIdentity("myQuartzJob")
                .storeDurably()
                .build();
    }

    @Bean
    public Trigger jobTrigger() {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(5) // 每隔5秒执行一次
                .repeatForever();

        return TriggerBuilder.newTrigger()
                .forJob(quartzJobDetail())
                .withIdentity("myQuartzJobTrigger")
                .withSchedule(scheduleBuilder)
                .build();
    }
}

        5.运行应用,你将看到Quartz的定时任务每隔5秒执行一次,打印当前时间到控制台。

这些方式提供了多种选择,你可以根据项目的需求和复杂度来选择合适的方式来实现定时任务。使用@Scheduled注解更简单,而实现SchedulingConfigurer接口可以更灵活地自定义任务的配置。TaskScheduler适用于相对简单的任务调度需求,而Quartz适用于更复杂的任务调度需求,如支持Cron表达式、分布式任务等。

END

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是详细的步骤: 1. 首先,我们需要在pom.xml添加Quartz的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> ``` 2. 创建一个Job类,继承QuartzJobBean,并实现executeInternal方法。该方法就是我们要执行的任务逻辑。 ``` public class MyJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { // 任务逻辑 } } ``` 3. 创建一个实现SchedulingConfigurer接口的定时任务配置类。该类可以动态添加定时任务,也可以从数据库、配置文件等读取定时任务。 ``` @Configuration public class QuartzConfig implements SchedulingConfigurer { @Autowired private ApplicationContext applicationContext; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { // 从数据库或配置文件读取定时任务 // ... // 动态添加定时任务 taskRegistrar.addTriggerTask( () -> { MyJob myJob = applicationContext.getBean(MyJob.class); myJob.executeInternal(null); }, triggerContext -> { // 定时任务表达式 CronTrigger cronTrigger = new CronTrigger("0/5 * * * * ?"); return cronTrigger.nextExecutionTime(triggerContext); } ); } } ``` 4. 在Spring Boot主类上加上@EnableScheduling注解,启用定时任务。 ``` @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,我们就可以使用QuartzJobBean+SchedulingConfigurer实现动态添加定时任务了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

missterzy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值