天天看點

SpringBoot使用Quartz 定時器任務排程配置

1、先在pom.xml裡面配置quartz的依賴包

<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<exclusions>
<exclusion>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
</exclusion>
</exclusions>
</dependency>
           

2、可以跟Service/Controller檔案夾并其建立一個檔案夾命名為schedule,裡面建一個檔案QuartzJob

@Component

@EnableScheduling

@Async

@DisallowConcurrentExecution

public class QuartzJob {
   

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());   

     
    //測試用

    @Scheduled(cron = "0 */5 * * * ?")

  public void updateDingingNum2() throws Exception {

        //抓取每個餐廳的就餐人數

      logger.info("----------每5分鐘執行一次-----------------");

        logger.info("每5分鐘========"+Thread.currentThread().getId()+new Date());

        UserBehaveService dingService = ContextHolder.getBean(UserBehaveService.class);

        dingService.useraction(); //soap方式,調的是service裡你想要排程的的方法

  }

}
           

@Scheduled(cron = "0 0 6 * * *") // 每天早上6點觸發

或者  @Scheduled(cron = "0 0 17 * * *") // 每天下午5點觸發

或者  @Scheduled(cron = "0 */2 * * * ?") // 每2分鐘執行一次

另外可以與QuartzJob檔案并列建立一個連接配接池檔案

@Configuration

@EnableAsync

public class TaskExecutorConfig implements AsyncConfigurer {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());   

    @Override

    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();

        // 如果池中的實際線程數小于corePoolSize,無論是否其中有空閑的線程,都會給新的任務産生新的線程

        taskExecutor.setCorePoolSize(5);

        // 連接配接池中保留的最大連接配接數。Default: 15 maxPoolSize

        taskExecutor.setMaxPoolSize(10);

        // queueCapacity 線程池所使用的緩沖隊列

        taskExecutor.setQueueCapacity(25);

        // rejection-policy:當pool已經達到max size的時候,如何處理新任務

        // CALLER_RUNS:不在新線程中執行任務,而是由調用者所在的線程來執行

        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        taskExecutor.initialize();

        return taskExecutor;
    }



    @Override

    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {

        return new AsyncUncaughtExceptionHandler() {

            @Override

            public void handleUncaughtException(Throwable ex, Method method, Object... params) {

                logger.error("=========================="+ex.getMessage()+"=======================", ex);  

                logger.error("exception method:"+method.getName());  

            }

        };

    }

}
           

繼續閱讀