@EnableScheduling注解


@EnableScheduling 开启对定时任务的支持

      其中Scheduled注解中有以下几个参数:

  1.cron是设置定时执行的表达式,如 0 0/5 * * * ?每隔五分钟执行一次 秒 分 时 天 月

  2.zone表示执行时间的时区

  3.fixedDelay 和fixedDelayString 表示一个固定延迟时间执行,上个任务完成后,延迟多长时间执行

  4.fixedRate 和fixedRateString表示一个固定频率执行,上个任务开始后,多长时间后开始执行

  5.initialDelay 和initialDelayString表示一个初始延迟时间,第一次被调用前延迟的时间

配置类

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@ComponentScan({"com.xingguo.logistics.service.aspect")

@EnableScheduling
public class AopConfig{

}

service类

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

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

@Service
public class TestService2 {

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

//初始延迟1秒,每隔2秒
@Scheduled(fixedRateString = "2000",initialDelay = 1000)
public void testFixedRate(){
System.out.println("fixedRateString,当前时间:" +format.format(new Date()));
}

//每次执行完延迟2秒
@Scheduled(fixedDelayString= "2000")
public void testFixedDelay(){
System.out.println("fixedDelayString,当前时间:" +format.format(new Date()));
}

//每隔3秒执行一次
@Scheduled(cron="0/3 * * * * ?")
public void testCron(){
System.out.println("cron,当前时间:" +format.format(new Date()));
}
}

测试类

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestController {

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

}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM