适用于Sping3.1以后的版本,首先通过注解@EnableScheduling开启对计划任务的支持,然后在计划任务的方法上添加注解@Scheduled来申明这是一个计划任务。

Spring通过@Scheduled支持多种类型的计划任务,包含cron,fixDelay,fixRate等


demo~

1.计划任务执行类

package com.xjj.task;

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

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

/**
 * SpringBoot
 * Created by xian.juanjuan on 2017-6-12 14:02.
 */
@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");

    @Scheduled(fixedDelay = 2000)
    public void runFixedRateTime(){
        System.out.println("每隔两秒执行一次"+dateFormat.format(new Date()));
    }

    @Scheduled(cron = "0 2 14 ? * *")//每天14点12分执行,cron是Linux和Unix系统下的定时任务
    public void runCron(){
       System.out.println("在指定时间执行"+dateFormat.format(new Date()));
    }
}

2.配置类

package com.xjj.task;

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

/**
 * SpringBoot
 * Created by xian.juanjuan on 2017-6-12 14:08.
 */
@Configuration
@ComponentScan("com.xjj.task")
@EnableScheduling
public class ScheduledConfig {

}

3.运行

package com.xjj.task;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * SpringBoot
 * Created by xian.juanjuan on 2017-6-12 14:09.
 */
public class Main {
    public static void main(String[] args){
        new AnnotationConfigApplicationContext(ScheduledConfig.class);
    }
}
结果

Spring计划任务(定时任务)


相关文章: