Spring Boot中几种定时任务

Timer类

public static void main(String[] args){
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				System.out.println("Timer方式执行一次定时任务");
			}
		};
		new Timer().schedule(timerTask,1,2*1000);
	}

ScheduledExecutorService类

ScheduledExecutorService,是基于线程设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去并行执行

public static void main(String[] args){
		ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutor.scheduleAtFixedRate(
				new Runnable() {
					@Override
					public void run() {
						System.out.println("ScheduledExecutorService方式执行一次定时任务");
					}
				}
		,0,5, TimeUnit.SECONDS);
	}

Quartz

  1. 引入quartz依赖

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>
    
  2. 配置JobDetail和Trigger

    @Configuration
    public class QuartzConfig {
        @Bean
        public JobDetail quartzDetail(){
            return JobBuilder.newJob(QuartzTest.class).withIdentity("QuartzTest").storeDurably().build();
        }
        @Bean
        public SimpleTrigger quartzTrigger(){
            SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(10)
                    .repeatForever();
            //CronScheduleBuilder cron= CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
            return TriggerBuilder.newTrigger().forJob(quartzDetail())
                    .withIdentity("QuartzTest")
                    .withSchedule(scheduleBuilder)
                    .build();
        }
    }
    
    
  3. 测试

    public class QuartzTest extends QuartzJobBean {
        @Override
        protected void executeInternal(JobExecutionContext jobExecutionContext){
            System.out.println("quartz执行一次定时任务 ");
        }
    }
    

Scheduled注解

  1. Spring3.0以后自带的task,在启动类上使用@EnableScheduling开启定时任务支持

  2. 使用

    @Component
    public class ScheduledTest {
        private Logger logger = LoggerFactory.getLogger(ScheduledTest.class);
        /**
         * 每3秒执行一次定时任务
         */
       @Scheduled(fixedRate = 3000) 
        public void testCron(){
            logger.info("Scheduled 执行一次定时任务");
        }
    }
    
  3. @Scheduled(initialDelay = 1000, fixedRate = 3000) 第一次延迟1秒后执行,之后按 fixedRate 的规则每 3 秒执行一次

  4. @Scheduled(cron = "0/10 * * * * ? ")通过 cron 表达式定义规则

上一篇:Spring Boot中整合Quartz实现定时任务


下一篇:IDEA使用springboot自带scheduled实现任务调度