码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Boot教程11——计划任务

时间:2016-09-24 13:26:13      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

从Spring3.1开始,计划任务在Spring中的实现变得异常的简单。首先通过在配置类注解@EnableScheduling来开启对计划任务的支持,然后在要执行计划任务的方法上注解@Scheduled声明这是一个计划任务。
Spring通过@Scheduled支持多种类型的计划任务,包含cron、fixDelay、fixRatedeng。

示例

1>.计划任务执行类

package com.wisely.highlight_spring4.ch3.taskscheduler;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledTaskService {
    
      private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

      @Scheduled(fixedRate = 5000) //通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行
      public void reportCurrentTime() {
           System.out.println("每隔5秒执行一次 " + dateFormat.format(new Date()));
       }

      @Scheduled(cron = "0 28 11 ? * *"  ) //使用cron属性可按指定时间执行,本例指的是11点28分执行;cron是UNIX和类UNIX(如Linux)系统下的定时任务
      public void fixTimeExecution(){
          System.out.println("在指定时间 " + dateFormat.format(new Date())+"?执行");
      }

}

 

2>.配置类

package com.wisely.highlight_spring4.ch3.taskscheduler;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.taskscheduler")
@EnableScheduling //开启对计划任务的支持
public class TaskSchedulerConfig {

}

 

3>.运行

package com.wisely.highlight_spring4.ch3.taskscheduler;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
         AnnotationConfigApplicationContext context =
                    new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
         
    }

}

 

Spring Boot教程11——计划任务

标签:

原文地址:http://www.cnblogs.com/quickcodes/p/Spring-Boot-jiao-cheng11ji-hua-ren-wu.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!