/**
*@author StormMaybin
*@date 2017-01-28
*/
生命不息喻旷,奮斗不止煞赢!
Spring 定時(shí)任務(wù)介紹
從spring 3.1開(kāi)始以故,計(jì)劃任務(wù)在Spring中的實(shí)現(xiàn)變得異常的簡(jiǎn)單屯耸,首先通過(guò)類(lèi)注解@EnableScheduing 來(lái)開(kāi)啟對(duì)計(jì)劃任務(wù)的支持!然后在要執(zhí)行的計(jì)劃任務(wù)上面添加@Scheduled送丰,聲明這是一個(gè)計(jì)劃任務(wù)缔俄!
計(jì)劃執(zhí)行類(lèi)
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("每隔五秒鐘執(zhí)行一次: " + dateFormat.format(new Date()));
}
@Scheduled(cron = "0 28 11 ? * *")
public void fixTimeExecution() {
System.out.println("在指定時(shí)間 " + dateFormat.format(new Date()) + "執(zhí)行");
}
}
配置類(lèi)
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 {
}
運(yùn)行類(lèi)
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);
}
}