SpringBoot Schedule 配置,springbootschedule

來源:互聯網
上載者:User

SpringBoot Schedule 配置,springbootschedule
1. 定時任務實現方式

定時任務實現方式:

  • Java內建的java.util.Timer類,這個類允許你調度一個java.util.TimerTask任務。使用這種方式可以讓你的程式按照某一個頻度執行,但不能在指定時間運行。一般用的較少,這篇文章將不做詳細介紹。
  • 使用Quartz,這是一個功能比較強大的的調度器,可以讓你的程式在指定時間執行,也可以按照某一個頻度執行,配置起來稍顯複雜,有空介紹。
  • 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;@Componentpublic 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@EnableSchedulingpublic 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@EnableSchedulingpublic 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 implementsAsyncConfigurer, SchedulingConfigurer {@Beanpublic ThreadPoolTaskScheduler taskScheduler(){ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();scheduler.setPoolSize(20);scheduler.setThreadNamePrefix("task-");scheduler.setAwaitTerminationSeconds(60);scheduler.setWaitForTasksToCompleteOnShutdown(true);return scheduler;}@Overridepublic Executor getAsyncExecutor(){Executor executor = this.taskScheduler();return executor;}@Overridepublic void configureTasks(ScheduledTaskRegistrar registrar){TaskScheduler scheduler = this.taskScheduler();registrar.setTaskScheduler(scheduler);}}

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

@SpringBootApplicationpublic class Application {    public static void main(String[] args) throws Exception {             AnnotationConfigApplicationContext rootContext =     new AnnotationConfigApplicationContext();    rootContext.register(RootContextConfiguration.class);    rootContext.refresh();    }}

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.