Spring定时任务

作者: StormMa | 来源:发表于2017-03-15 23:04 被阅读0次
    /**
    *@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定时任务

        本文链接:https://www.haomeiwen.com/subject/bkornttx.html