Spring 计划任务

每个人的生活总是有存在以下规律,在固定的时间起床,在固定的时间吃饭。程序的执行也是可以有规律的。

从Spring3.1开始,计划任务在Spring中的实现变得异常简单。首先通过在配置类添加注解@EnableScheduling来开启程序对计划任务的支持,然后在要作为计划任务执行的方法上注解@Scheduled,声明这是一个计划任务。

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

示例

(1)修改配置类,添加计划任务支持

package learnspring.learnspring.schedule;

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

/**
 * @author 肖政宇
 * @date 2019-09-24 10:42
 * 说明:配置类
 */
@Configuration
@EnableScheduling
public class ScheduleConfiguration {
}

(2)计划任务执行类

package learnspring.learnspring.schedule;

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

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

/**
 * @author 肖政宇
 * @date 2019-09-24 10:35
 * 说明:计划任务执行类
 */
@Service
public class ScheduleTaskService {
    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");

    /**
     * 通过@Scheduled声明该方法是计划任务
     * fixedRate设置任务按照固定时间间隔执行
     */
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println(String.format("每隔5秒执行一次 " + SIMPLE_DATE_FORMAT.format(new Date())));
    }

    /**
     * 使用cron设置任务在指定时间执行
     * 下例指的是每天11点28分执行。
     */
    @Scheduled(cron = "0 28 11 ? * *")
    public void fixTimeExecution() {
        System.out.println("在指定的时间 " + SIMPLE_DATE_FORMAT.format(new Date() + "执行"));
    }
}

(3)执行程序

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值