@EnableScheduling和@Scheduled的使用

定时任务在配置类上添加@EnableScheduling开启对定时任务的支持,在相应的方法上添加@Scheduled声明需要执行的定时任务。
其中Scheduled注解中有以下几个参数:

  1. cron
  2. zone
  3. fixedDelay和fixedDelayString
  4. fixedRate和fixedRateString
  5. initialDelay和initialDelayString

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

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

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

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

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

配置类

package com.xingguo.logistics.controller;

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类

package com.xingguo.logistics.service.aspect;

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()));
    }
}

测试类

package com.xingguo.logistics.controller;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestController {

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

    }
}

测试结果:
这里写图片描述

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值