定时任务

2016-12-24
  • 定时任务实现方式
    • Java中的java.util.Timer与java.util.TimerTask
    • Quartz
    • SpringBoot中的Scheduled

springboot定时任务

  • 定义任务

    @Component
    public class ScheduleJob {
    
        @Scheduled(cron="0 0/2 8-20 * * ?") 
        public void job1() {
            //间隔2分钟执行任务
        }
    
        @Scheduled(cron="0 0/1 8-20 * * ?") 
        public void job2() {
            // 间隔1分钟执行任务 
        }
    }
    
  • 启动任务

    @EnableScheduling
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
  • 并行执行

    • springboot的schedule默认串行执行,要支持并行,需在applicationContext.xml中添加如下内容

      <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xmlns:task="http://www.springframework.org/schema/task"
          xmlns:context="http://www.springframework.org/schema/context"
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
      
          <!-- Enables the Spring Task @Scheduled programming model -->
          <task:executor id="executor" pool-size="5" />
          <task:scheduler id="scheduler" pool-size="10" />
          <task:annotation-driven executor="executor" scheduler="scheduler" />
      
      </beans>
      

Kommentare: