SpringBoot Schedule 配置

1. 定時任務實現方式

定時任務實現方式:java

  • Java自帶的java.util.Timer類,這個類容許你調度一個java.util.TimerTask任務。使用這種方式能夠讓你的程序按照某一個頻度執行,但不能在指定時間運行。通常用的較少,這篇文章將不作詳細介紹。
  • 使用Quartz,這是一個功能比較強大的的調度器,能夠讓你的程序在指定時間執行,也能夠按照某一個頻度執行,配置起來稍顯複雜,有空介紹。
  • SpringBoot自帶的Scheduled,能夠將它當作一個輕量級的Quartz,並且使用起來比Quartz簡單許多,本文主要介紹。

定時任務執行方式:spring

  • 單線程(串行)
  • 多線程(並行)

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,都是一個線程串行執行,並行需手動配置ide

4. 並行任務

繼承SchedulingConfigurer類並重寫其方法便可,以下:this

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

再次執行以前的那個Demo,會欣然發現已是並行執行了!  線程

 

4. 異步並行任務

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;

@Configuration
@EnableScheduling
@EnableAsync(
mode = AdviceMode.PROXY, proxyTargetClass = false,
order = Ordered.HIGHEST_PRECEDENCE
)
@ComponentScan(
basePackages = "hello"
)
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);
}
}

在啓動的main方法加入額外配置:blog

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
    
    
     AnnotationConfigApplicationContext rootContext =
     new AnnotationConfigApplicationContext();

    rootContext.register(RootContextConfiguration.class);
    rootContext.refresh();
    }
}
相關文章
相關標籤/搜索