Spring定时任务

/**
*@author StormMaybin
*@date 2017-01-28
*/

生命不息,奋斗不止!


Spring 定时任务介绍

从spring 3.1开始,计划任务在Spring中的实现变得异常的简单,首先通过类注解@EnableScheduing 来开启对计划任务的支持!然后在要执行的计划任务上面添加@Scheduled,声明这是一个计划任务!

计划执行类

ScheduledTaskService.java

package com.stormma.service;

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

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

/**
 * <p>Created by StormMa on 2017/1/28.</p>
 *
 * @author StormMa
 */
@Service
public class ScheduledTaskService {

    private static final SimpleDateFormat dateFormat = new
            SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("每隔五秒钟执行一次: " + dateFormat.format(new Date()));
    }

    @Scheduled(cron = "0 28 11 ? * *")
    public void fixTimeExecution() {
        System.out.println("在指定时间 " + dateFormat.format(new Date()) + "执行");
    }
}

配置类

MyConfig.java

package com.stormma.config;

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

/**
 * <p>Created by StormMa on 2017/1/28.</p>
 *
 * @author StormMa
 */
@Configuration
@EnableScheduling
@ComponentScan("com.stormma")
public class MyConfig {
}

运行类

Client.java

package com.stormma.client;

import com.stormma.config.MyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * <P>Created by StormMa on 2017/1/28.</P>
 *
 * @author StormMa
 */
public class Client {

    public static void main(String [] args) {
        AnnotationConfigApplicationContext context = new
                AnnotationConfigApplicationContext(MyConfig.class);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,841评论 18 139
  • 本文参考自Spring官方文档 34. Task Execution and Scheduling。 在程序中常常...
    乐百川阅读 5,573评论 0 11
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,926评论 6 342
  • 因为喜欢所以坚持! 好或者不好,我都会坚持练习下去,练习下去!(开什么玩笑!这个当然算不上好!练习是真!)
    秋日暖阳中的银杏叶阅读 398评论 1 3
  • 文/鬼谷 一 江山蓝图绘新篇,舞动乾坤展蹁跹。 中国梦承十八大,京城会师又一年。 小康大计勇向前,万紫千红逐开妍。...
    鬼谷阳阅读 146评论 0 0