SpringBoot Schedule 配置

本文介绍SpringBoot中定时任务的实现方法,包括使用Scheduled注解配置定时任务、启动任务及并行任务的实现。通过实例展示了如何设置定时任务的执行频率、启动方式,并提供了并行任务的具体配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、定时任务实现方式:

SpringBoot自带的Scheduled,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多,本文主要介绍。
定时任务执行方式:

单线程(串行)
多线程(并行)

2、 创建定时任务

package com.autonavi.task.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.autonavi.task.ScheduledTasks;

@Component
public class ScheduledTest {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);

    @Scheduled(cron="0 0/2 * * * ?")
    public void executeFileDownLoadTask() {

        // 间隔2分钟,执行任务    
        Thread current = Thread.currentThread(); 
        System.out.println("定时任务1:"+current.getId());
        logger.info("ScheduledTest.executeFileDownLoadTask 定时任务1:"+current.getId()+ ",name:"+current.getName());
    }
}


@Scheduled 注解用于标注这个方法是一个定时任务的方法,有多种配置可选。
cron支持cron表达式,指定任务在特定时间执行;
fixedRate以特定频率执行任务;fixedRateString以string的形式配置执行频率。

3、启动定时任务

@SpringBootApplication
@EnableScheduling
public class App {

    private static final Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {

        SpringApplication.run(App.class, args);    
        logger.info("start");                       
    }  
}

其中 @EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。

Springboot本身默认的执行方式是串行执行,也就是说无论有多少task,都是一个线程串行执行,并行需手动配置

4. 并行任务
继承SchedulingConfigurer类并重写其方法即可,如下:

@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod="shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    }
}

4. 异步并行任务
继承SchedulingConfigurer类并重写其方法即可,如下:

package com.oyb.springbootmybatis.Schedule;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 *
 */
@Configuration
@EnableScheduling
@EnableAsync(
        mode = AdviceMode.PROXY, proxyTargetClass = false,
        order = Ordered.HIGHEST_PRECEDENCE
)
@ComponentScan(
        basePackages = "com.oyb.springbootmybatis.Schedule"
)
public class RootContextConfiguration implements AsyncConfigurer,SchedulingConfigurer {


    @Bean
    public ThreadPoolTaskScheduler taskScheduler()
    {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(20);
        scheduler.setThreadNamePrefix("task-");
        scheduler.setAwaitTerminationSeconds(60);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        return scheduler;
    }

    @Override
    public Executor getAsyncExecutor()
    {
        Executor executor = this.taskScheduler();
        return executor;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar registrar)
    {
        TaskScheduler scheduler = this.taskScheduler();
        registrar.setTaskScheduler(scheduler);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

在启动的main方法加入额外配置:

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {


     AnnotationConfigApplicationContext rootContext =
     new AnnotationConfigApplicationContext();

    rootContext.register(RootContextConfiguration.class);
    rootContext.refresh();
    }
}

转载:https://www.cnblogs.com/slimer/p/6222485.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值